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();
相关推荐
犀利豆16 分钟前
AI in Harness(二)
java·人工智能·后端
IT_陈寒20 分钟前
Python装饰器竟然偷偷改了函数名?这个坑我爬了三天
前端·人工智能·后端
bkl_92131 小时前
GPT-Image-2 文生图:如何稳定生成完整的人物全身照?
后端·gpt·restful
jy1 小时前
支付后端研发的 AI 工作流实践:巡检、排查、开发全流程落地
后端·ai编程
GoGeekBaird2 小时前
我最近在写 BeeWeave,想把 Agent 用过的上下文留住
后端·github·ai编程
醇氧2 小时前
Spring 容器 Map 注入机制详解
java·后端·spring
梨子同志2 小时前
MyBatis-Plus
后端
doiito2 小时前
微服务资源优化新思路:Sablier + Podman 实现按需启动与自动休眠
后端·微服务·性能优化
接着奏乐接着舞。2 小时前
【2026年7月最新】69道RAG面试题
前端·人工智能·后端·aigc·embedding·rag