Serilog使用方法
参考资源:
https://www.cnblogs.com/pangjianxin/p/9428900.html
https://www.cnblogs.com/RainFate/p/12073662.html //这篇讲解的更好
step1 在vs中用Nuget安装 Serilog.AspNetCore、Serilog.Sinks.File
step2
修改Programe.cs如下
[方案一:]
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace MyRabbitMQ
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
//最小的输出单位是Debug级别的
.MinimumLevel.Debug()
/*
* 未实现这种方式的记录
//将Microsoft前缀的日志的最小输出级别改成Information
.MinimumLevel.Override("MicroSoft", LogEventLevel.Information)
.Enrich.FromLogContext()
*/
//输出到控制台
.WriteTo.Console()
//将日志输出到目标路径,文件的生成方式为每天生成一个文件
.WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log",
rollingInterval: RollingInterval.Day)
.CreateLogger();
try
{
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application Start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
/*
* 去掉默认日志
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
})
*/
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog();
}
}
[方案二:]
namespace MyRabbitMQ
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.File($"{AppContext.BaseDirectory}00_Logs\\log.log", rollingInterval: RollingInterval.Day)
.WriteTo.Console();
});
}
}