前言
一、什么是Serilog?
二、如何安装Serilog?
Install-Package Serilog.AspNetCore
三、如何配置Serilog?
3.1Program的配置如下
- Configuration:构建对象,读取appsettings.json的配置文件
- Log.Logger:读取Configuration中的日志配置信息,然后设置输出的级别、内容、位置等。
- UseSerilog(dispose:true):引入Serilog框架,dispose:true=>系统退出时,释放日志对象
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())//设置基础路径
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)//添加配置文件
.AddEnvironmentVariables()//添加环境变量
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
.MinimumLevel.Debug()
.Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
.WriteTo.Console(new RenderedCompactJsonFormatter())//输出到控制台
.WriteTo.File(formatter:new CompactJsonFormatter(),"logs\\test.txt",rollingInterval:RollingInterval.Day)//输出到文件
.CreateLogger();//清除内置日志框架
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex,"Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).
.ConfigureWebHostDefaults(webBuilder =>{
webBuilder.UseStartup<Startup>();
}).UseSerilog(dispose:true);//引入第三方日志框架
3.2 appsettings.json配置
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Information"
}
}
}
}
四、如何使用Serilog?
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public void Get()
{
_logger.LogInformation("LogInformation" + Guid.NewGuid().ToString("N"));
_logger.LogDebug("LogDebug" + Guid.NewGuid().ToString("N"));
_logger.LogWarning("LogWarning" + Guid.NewGuid().ToString("N"));
_logger.LogError("LogError" + Guid.NewGuid().ToString("N"));
}
五、展示效果
控制台显示
文件显示
六、扩展
6.1分级别显示
//存储日志文件的路径
string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}00_Logs\{LogEvent}\log.log";
//存储日志文件的格式
string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 50);
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
.MinimumLevel.Debug()
.Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性丰富日志事件。
.WriteTo.Console(new RenderedCompactJsonFormatter())
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File(LogFilePath("Debug"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File(LogFilePath("Information"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(LogFilePath("Warning"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(LogFilePath("Error"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(LogFilePath("Fatal"), rollingInterval: RollingInterval.Day, outputTemplate: SerilogOutputTemplate))
.CreateLogger();
效果如下:
文件级别分类:
日志格式输出:
6.2存储到数据库
Install-Package Serilog.Sinks.MSSqlServer
修改配置
MSSqlServer(参数一,参数二,参数三,参数四)
- 数据库的地址
- 数据库中记录日志表的名称
- 是否自动创建表(Nlog是没有这个功能的)
- 记录日志最小级别
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
效果如下:
6.2.1数据库中表字段
新增
第一步:创建列
var options = new ColumnOptions();
options.AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
};
第二步:添加列
Enrich.WithProperty:添加属性
columnOptions: options:配置数据库的列
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
.MinimumLevel.Information()
.Enrich.WithProperty("IP", "2.2.2.2")
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, columnOptions: options, restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
第三步:运行即可
移除
第一步:记录移除列
StandardColumn:是框架默认提供数据库默认表,它的属性就是映射数据库的字段
var options = new ColumnOptions();
options.Store.Remove(StandardColumn.Properties);
options.Store.Remove(StandardColumn.TimeStamp);
第二步:配置属性
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration)
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.WriteTo.MSSqlServer(connecting, "logs", autoCreateSqlTable: true, columnOptions: options, restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
第三步:运行即可
注意事项:
6.3发送到邮箱
添加安装包:
Install-Package Serilog.Sinks.Email
配置如下:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.WriteTo.Email(new EmailConnectionInfo() {
Port= 465,//端口
EmailSubject="邮件日志测试",//邮件主题
FromEmail= "[email protected]",//发件箱
ToEmail="[email protected]",//收件箱
MailServer= "smtp.163.com",//发件箱的邮箱服务
NetworkCredentials = new NetworkCredential("[email protected]", "zc960810"),//发件人的邮箱和密码
IsBodyHtml =true,//邮件是否是HTML格式
EnableSsl=true//使用启用SSL端口
})
.CreateLogger();
效果如下
总结
- .net core中的那些常用的日志框架(Logging篇)
- .net core中的那些常用的日志框架(NLog篇)
- .net core中的那些常用的日志框架(Serilog篇)
从其中,我学习了很多,了解了结构化日志,了解日志输出的多种方式,控制台、文件、数据库、邮箱,比以前只会写txt要进步不少。
三篇博客的源码地址