下载nuget包
Install-Package Serilog
Install-Package Serilog.AspNetCore
Install-Package Serilog.Settings.Configuration
Install-Package Serilog.Sinks.Console
Install-Package Serilog.Sinks.Debug
Install-Package Serilog.Sinks.File
Install-Package Serilog.Sinks.MSSqlServer
Install-Package Serilog.Sinks.RollingFile
在Program.cs程序启动时注入Serilog 加载配置
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000")
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.WriteTo.File(Path.Combine("logs", @"log.txt"), rollingInterval: RollingInterval.Day)
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console());
}
在appsettings.json配置文件
"Serilog": {
// 日志输出级别
"MinimumLevel": {
"Default": "Debug",
"Override": {
// 日志调用类命名空间如果以 Microsoft 开头,覆盖日志输出最小级别为 Information
"Microsoft": "Information",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "日志写入数据库的连接字符串",
//表名
"tableName": "Logs",
//自动创建表
"autoCreateSqlTable": true,
//记录日志级别
"restrictedToMinimumLevel": "Error"
}
}
]
},
使用
引用 using Serilog;
Log.Verbose(exp, msg); //最常见的记录信息,一般用于普通输出
Log.Debug(exp, msg); //同样是记录信息,不过出现的频率要比Verbose少一些,一般用来调试程序
Log.Information(exp, msg); //信息类型的消息
Log.Warning(exp, msg); //警告信息,一般用于比较重要的场合
Log.Error(exp, msg); //错误信息
Log.Fatal(exp, msg); //致命异常信息。一般来讲,发生致命异常之后程序将无法继续执行。
网友评论