ASP.NET Core's logging system

ASP.NET Core provides a rich logging system.
Logs can be output in various ways to meet different scenarios. Several built-in log systems include:

  • Console, output to the console, used for debugging, may affect performance in the production environment.
  • Debug, output to System.Diagnostics.Debug.WriteLine
  • EventSource, output to the log system of the corresponding operating system, and output to ETW on Windows.
  • EventLog, Windows specific, output to Windows Event Log.

It can be output to multiple log systems at the same time, or only to a certain log system, because all built-in log systems will be added by default. You can
specify the output to the console through the following code:

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

Third-party file-based logging systems:

  • Log4Net
  • Log
  • Serilog

Set the log output to the Serilog file log system, but Serilog will prevent the output of the console log,

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

Then when using it, you can inject and use the Log class in each class:

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());
    }
}

Note that logs are categorized into AboutModel for easy search.

log level

The higher the level, the less output, until nothing is output.

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

For example, in appsettings.json configuration, Console only outputs logs above Information, EventSource only outputs logs above Warning, and all others output logs above 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

You can set the ID of the Log to further distinguish different logs:

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);

Output the log before the App runs

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();

Log HTTP requests

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