ASP.NET Core 的日志系统

ASP.NET Core 提供了丰富日志系统。

可以通过多种途径输出日志,以满足不同的场景,内置的几个日志系统包括:

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

可以同时输出到多个日志系统,也可以只输出到某一个日志系统,因为默认会添加所有内置的日志系统

可以通过下面的代码指定输出到控制台:

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

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

  • Log4Net
  • NLog
  • Serilog

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

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

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

csharp 复制代码
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以上的。

javascript 复制代码
{
  "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进一步区分不同的日志:

csharp 复制代码
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;
}
csharp 复制代码
_logger.LogInformation(MyLogEvents.GetItem, "Getting item {Id}", id);

输出 App 运行之前的日志

csharp 复制代码
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 请求

csharp 复制代码
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();
相关推荐
码出极致5 分钟前
Java中的AQS概念、原理和使用
后端
满分观察网友z11 分钟前
告别CRUD Boy!SQL子查询:从头疼到真香的进化之路
数据库·后端
天天摸鱼的java工程师11 分钟前
volatile关键字实战指南:八年Java开发者详解五大应用场景
java·后端
满分观察网友z19 分钟前
告别满屏if-else!我如何用注解和AutoCloseable徒手撸一个校验框架?
后端
程序员爱钓鱼2 小时前
Go语言统计字符串中每个字符出现的次数 — 简易频率分析器
后端·google·go
Code季风2 小时前
深度优化 spring 性能:从缓存、延迟加载到并发控制的实战指南
java·spring boot·后端·spring·缓存·性能优化
风象南2 小时前
SpringBoot自定义RestTemplate的拦截器链
java·spring boot·后端
Victor3563 小时前
MySQL(138)如何设置数据归档策略?
后端
Victor3563 小时前
MySQL(137)如何进行数据库审计?
后端
FreeBuf_11 小时前
黄金旋律IAB组织利用暴露的ASP.NET机器密钥实施未授权访问
网络·后端·asp.net