交通设施东莞网站建设,深圳观澜网站建设,怎么做送餐网站,wordpress tinctionASP.NET Core 提供了丰富日志系统。 可以通过多种途径输出日志#xff0c;以满足不同的场景#xff0c;内置的几个日志系统包括#xff1a;
Console#xff0c;输出到控制台#xff0c;用于调试#xff0c;在产品环境可能会影响性能。Debug#xff0c;输出到 System.Di…ASP.NET Core 提供了丰富日志系统。 可以通过多种途径输出日志以满足不同的场景内置的几个日志系统包括
Console输出到控制台用于调试在产品环境可能会影响性能。Debug输出到 System.Diagnostics.Debug.WriteLineEventSource输出到对应操作系统的日志系统中在Windows上是输出到ETW中。EventLogWindows特有输出到Windows Event Log。
可以同时输出到多个日志系统也可以只输出到某一个日志系统因为默认会添加所有内置的日志系统 可以通过下面的代码指定输出到控制台
var builder WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders(); //清除其他日志输出系统
builder.Logging.AddConsole(); //输出到控制台第三方的文件为主的日志系统
Log4NetNLogSerilog
设置日志输出到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(ILoggerAboutModel logger){_logger logger;}public void OnGet(){_logger.LogInformation(About page visited at {DT}, DateTime.UtcNow.ToLongTimeString());}
}注意这里会把日志分类成 AboutModel以便查找。
日志的级别
级别越高输出的内容越少直到什么都不输出。
TraceDebugInformationWarningErrorCriticalNone
比如在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 providerLogLevel: {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();