C# 中如何定制.NET6.0的日志记录

科技资讯 投稿 56300 0 评论

C# 中如何定制.NET6.0的日志记录

在本章,我们将介绍以下主题:配置日志记录,创建自定义日志记录,使用第三方日志框架。

技术要求

dotnet new mvc -n LoggingSample -o LoggingSample

在中双击打开该项目,或者在控制台中键入以下命令用打开该项目:

cd LoggingSample code .

配置日志记录

在的早期版本中(即2.0版之前的版本),日志记录是在配置的。之后文件慢慢简化,许多配置被移动到的,日志记录也是在这个时候被移动到。

public class Program {     
    public static void Main(string[] args
    {         
        CreateHostBuilder(args.Build(.Run(;     
    }     
    
    public static IHostBuilder CreateHostBuilder(string[] args =>
        Host.CreateDefaultBuilder(args.ConfigureWebHostDefaults(webBuilder => 
        { 
            webBuilder.UseStartup<Startup>(;
        }; 
}

在中,引入了简化配置的迷你API()方法。这种方法不使用文件,而是将所有配置添加到文件,如下代码段:

var builder = WebApplication.CreateBuilder(args; 

//添加服务到容器.
builder.Services.AddControllersWithViews(; 
var app = builder.Build(; 
…

在,您可以覆盖和自定义几乎所有内容,包括日志记录。有很多扩展方法,允许我们覆盖不同功能的默认行为。要覆盖日志记录的默认设置,我们需要使用方法。

Host.CreateDefaultBuilder(args.ConfigureWebHostDefaults(webBuilder =>{         
    webBuilder.ConfigureLogging((hostingContext, logging => {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging";                 
        logging.AddConsole(;                 
        logging.AddDebug(;             
    }.UseStartup<Startup>(;

使用方法,我们不再需要方法,我们可以直接使用的属性:

builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"; 
builder.Logging.AddConsole(; 
builder.Logging.AddDebug(;

现在我们已经了解了如何配置日志记录,接下来我们看看如何自定义日志记录。

创建自定义日志记录

在接下来的代码片段中,将分别创建这三个关键类(、和):

1.ColoredConsoleLoggerConfiguration

public class ColoredConsoleLoggerConfiguration 
{     
    public LogLevel LogLevel { get; set; } = LogLevel.Warning;     
    public int EventId { get; set; } = 0;    
    public ConsoleColor Color { get; set; } = ConsoleColor.Yellow; 
}

2.ColoredConsoleLoggerProvider

接下来,我们需要一个提供程序来检索配置并创建实际的日志记录实例

public class ColoredConsoleLoggerProvider : ILoggerProvider 
{     
    private readonly ColoredConsoleLoggerConfiguration _config;     
    private readonly ConcurrentDictionary<string, ColoredConsoleLogger> _loggers = new ConcurrentDictionary<string,ColoredConsoleLogger>(;     
    
    public ColoredConsoleLoggerProvider (ColoredConsoleLoggerConfiguration config 
    { 
        _config = config; 
    }     
    
    public ILogger CreateLogger(string categoryName 
    { 
        return _loggers.GetOrAdd(categoryName,name => new ColoredConsoleLogger(name, _config;     
    }
    
    public void Dispose( 
    {
        _loggers.Clear(; 
    } 
}

不要忘记引入

3.ColoredConsoleLogger

public class ColoredConsoleLogger : ILogger
{
    private static readonly object _lock = new Object(;
    private readonly string _name;
    private readonly ColoredConsoleLoggerConfiguration _config;

    public ColoredConsoleLogger(
        string name,
        ColoredConsoleLoggerConfiguration config
    {
        _name = name;
        _config = config;
    }

    public IDisposable BeginScope<TState>(TState state
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel
    {
        return logLevel == _config.LogLevel;
    }

    public void Log<TState>(
        LogLevel logLevel,
        EventId eventId,
        TState state,
        Exception exception,
        Func<TState, Exception, string> formatter
    {
        if (!IsEnabled(logLevel
        {
            return;
        }

        lock (_lock
        {
            if (_config.EventId == 0 || _config.EventId == eventId.Id
            {
                var color = Console.ForegroundColor;
                Console.ForegroundColor = _config.Color;
                Console.Write($"{logLevel} - ";
                Console.Write($"{eventId.Id} - {_name} - ";
                Console.Write($"{formatter(state, exception}\n";
                Console.ForegroundColor = color;
            }
        }
    }
}

我们现在需要(锁定 控制台的输出——这是因为控制台本身并不是真正的线程安全的,可能出现错误的着色。

using LoggingSample;

builder.Logging.ClearProviders(;
var config = new ColoredConsoleLoggerConfiguration
{
    LogLevel = LogLevel.Information,
    Color = ConsoleColor.Red
};
builder.Logging.AddProvider(new ColoredConsoleLoggerProvider(config;

首先需要向引入命名空间。

using LoggingSample;

如果不想使用现有的日志框架,可以清除之前添加的所有日志框架提供程序

builder.Logging.ClearProviders(;

然后,我们调用来添加实例。

下图显示了日志框架的彩色输出:

下面,我们将介绍如何在中使用。

使用第三方日志框架-NLog

1.配置

  1. 所有标准消息记录在一个日志文件中;

  2. 而自定义消息记录在另一个文件中

<targets>
     <!-- 标准消息 -->
     <target xsi:type="File" name="allfile" fileName="C:\git\dotnetconf\001-logging\nlog-all-${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

     
     <!-- 自定义消息 -->
     <target xsi:type="File" name="ownFile-web" fileName="C:\git\dotnetconf\001-logging\nlog-own-${shortdate}.log"
             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
      
     <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>

2.引入NuGet包

然后我们需要添加的包:

dotnet add package NLog.Web.AspNetCore

3.将与结合使用

清除方法中的其他提供程序,使用方法将与结合使用:

Host.CreateDefaultBuilder(args.ConfigureWebHostDefaults(webBuilder => {         
    webBuilder.ConfigureLogging((hostingContext,logging => {      
        //清除其他提供程序       
        logging.ClearProviders(;                 
        logging.SetMinimumLevel(LogLevel.Trace;             
    }.UseNLog(.UseStartup<Startup>(;     
};

使用看起来简单得多:

using NLog.Web; 

var builder = WebApplication.CreateBuilder(args; 

//清除其他提供程序  
builder.Logging.ClearProviders(; 
builder.Logging.SetMinimumLevel(LogLevel.Trace; 
builder.WebHost.UseNLog(;

在这里,您可以根据需要添加任意多个日志记录提供程序。

回顾 & 思考

  • 配置日志记录

  • 创建自定义日志记录

  • 使用第三方日志框架

思考:我们应该如何自定义应用的配置?欢迎关注下篇内容《如何自定义.NET 6.0的应用配置》。

编程笔记 » C# 中如何定制.NET6.0的日志记录

赞同 (36) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽