ASP.NET Core 的日志系统

ASP.NET Core 提供了丰富日志系统。
可以通过多种途径输出日志,以满足不同的场景,内置的几个日志系统包括:

  • Console,输出到控制台,用于调试,在产品环境可能会影响性能。
  • Debug,输出到 System.Diagnostics.Debug.WriteLine
  • EventSource,输出到对应操作系统的日志系统中,在Windows上是输出到ETW中。
  • EventLog,Windows特有,输出到Windows Event Log。

可以同时输出到多个日志系统,也可以只输出到某一个日志系统,因为默认会添加所有内置的日志系统
可以通过下面的代码指定输出到控制台:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); //清除其他日志输出系统
builder.Logging.AddConsole(); //输出到控制台

第三方的文件为主的日志系统:

  • Log4Net
  • NLog
  • Serilog

设置日志输出到Serilog文件日志系统,但是Serilog会阻止控制台日志的输出,

Log.Logger = new LoggerConfiguration().WriteTo.File(Config.PathLogFile,
                                    fileSizeLimitBytes: 1024 * 1024 * 5,
                                    rollOnFileSizeLimit: true).CreateLogger();
            builder.Host.UseSerilog();
            var app = builder.Build();

然后用的时候,在每个类里都可以注入使用Log类:

public class AboutModel : PageModel
{
    
    
    private readonly ILogger _logger;
    public AboutModel(ILogger<AboutModel> logger)
    {
    
    
        _logger = logger;
    }
    public void OnGet()
    {
    
    
        _logger.LogInformation("About page visited at {DT}", DateTime.UtcNow.ToLongTimeString());
    }
}

注意,这里会把日志分类成 AboutModel,以便查找。

日志的级别

级别越高,输出的内容越少,直到什么都不输出。

  1. Trace
  2. Debug
  3. Information
  4. Warning
  5. Error
  6. Critical
  7. None

比如在appsettings.json配置中,Console只输出Information以上的日志, EventSource只输出Warning以上的日志,其他所有的输出Error以上的。

{
    
    
  "Logging": {
    
    
    "LogLevel": {
    
     // All providers, LogLevel applies to all the enabled providers.
      "Default": "Error", // Default logging, Error and higher.
      "Microsoft": "Warning" // All Microsoft* categories, Warning and higher.
    },
    "Console": {
    
     // Debug provider.
      "LogLevel": {
    
    
        "Default": "Information", // Overrides preceding LogLevel:Default setting.
        "Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.
      }
    },
    "EventSource": {
    
     // EventSource provider
      "LogLevel": {
    
    
        "Default": "Warning" // All categories of EventSource provider.
      }
    }
  }
}

Log的ID

可以设置Log的ID进一步区分不同的日志:

public class MyLogEvents
{
    
    
    public const int GenerateItems = 1000;
    public const int ListItems     = 1001;
    public const int GetItem       = 1002;
    public const int InsertItem    = 1003;
    public const int UpdateItem    = 1004;
    public const int DeleteItem    = 1005;
    public const int TestItem      = 3000;
    public const int GetItemNotFound    = 4000;
    public const int UpdateItemNotFound = 4001;
}
_logger.LogInformation(MyLogEvents.GetItem, "Getting item {Id}", id);

输出 App 运行之前的日志

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Logger.LogInformation("Adding Routes");
app.MapGet("/", () => "Hello World!");
app.Logger.LogInformation("Starting the app");
app.Run();

记录 HTTP 请求

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpLogging(); //启用Http log系统
if (!app.Environment.IsDevelopment())
{
    
    
    app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.MapGet("/", () => "Hello World!");
app.Run();

猜你喜欢

转载自blog.csdn.net/cuit/article/details/132568270