日志组件Serilog使用
NuGet 安装 Serilog
核心的包是 Serilog 和 Serilog.AspNetCore
建议安装 Serilog.AspNetCore,几乎包含了Serilog常用的所有包
异步写入 Serilog.Sinks.Async
写入MSSQL Serilog.Sinks.MSSqlServer
Install-Package Serilog.AspNetCore
Install-Package Serilog # winform 安装
Install-Package Serilog.Sinks.Async
Install-Package Serilog.Sinks.MSSqlServer
日志输出控制台
public static void Test1()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console() //输出到控制台
.CreateLogger();
Log.Information("Info输出到控制台测试!");
Log.Debug("Debug输出控制台测试!");
Log.Error("Error错误信息输出");
Log.Warning("Warning警告信息输出");
}
日志输出到文件
public static void Test2()
{
/*
WriteTo.File详解
path:默认路径是程序的bin目录+path参数,当然也可以写绝对路径,只需要写入参数就可以了
rollingInterval:创建文件的类别,可以是分钟,小时,天,月。 此参数可以让创建的log文件名 + 时间。例如log20191219.log
outputTemplate:日志模板,可以自定义
retainedFileCountLimit:设置日志文件个数最大值,默认31,意思就是只保留最近的31个日志文件,等于null时永远保留文件
*/
//同步输出到本地文件
//日志模板
string SerilogOutputTemplate = "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 100);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug() // 所有Sink的最小记录级别
.WriteTo.Console() //输出到控制台
.WriteTo.File("Logs\\log.log", //$"{AppContext.BaseDirectory}Logs\log.log"
rollingInterval: RollingInterval.Day,
outputTemplate: SerilogOutputTemplate
, retainedFileCountLimit: 31
)
.CreateLogger();
Log.Information("Info输出到控制台测试!");
Log.Debug("Debug输出控制台测试!");
Log.Error("Error错误信息输出");
Log.Warning("Warning警告信息输出");
//异步输出到本地文件
Log.Logger = new LoggerConfiguration()
.WriteTo.Async(a => a.File("Logs\\log.log", rollingInterval: RollingInterval.Day))
.CreateLogger();
Log.Information("Info异步输出到控制台测试!");
Log.Debug("Debug异步输出控制台测试!");
Log.Error("Error异步错误信息输出");
Log.Warning("Warning异步警告信息输出");
Log.CloseAndFlush();
}
日志分等级输出到文件
public static void Test3()
{
string LogFilePath(string LogEvent) => $@"{AppContext.BaseDirectory}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()
.Enrich.FromLogContext()
.WriteTo.Console()
.MinimumLevel.Verbose() // 所有Sink的最小记录级别
.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();
Log.Information("Info输出到控制台测试!");
Log.Debug("Debug输出控制台测试!");
Log.Error("Error错误信息输出");
Log.Fatal("Fatal致命错误日志输出");
Log.Warning("Warning警告信息输出");
}
日志输出到数据库
public static void Test4()
{
try
{
string connectionString = @"Server=127.0.0.1\MSSQLSERVER19;Initial Catalog=RW_TEST;User ID=sa;Password=123456";
string tableNameA = "LogsA";
string tableNameB = "LogsB";
string tableNameC = "LogsC";
static void Write()
{
Log.Information("测试信息");
Log.Error("Error");
Log.Write(LogEventLevel.Error, new Exception("错误"), "致命错误");
};
//A:默认配置
//autoCreateSqlTable为true 时 会自动创建日志表
Log.Logger = new LoggerConfiguration().WriteTo.MSSqlServer(connectionString, tableNameA, autoCreateSqlTable: true).CreateLogger();
Write();
//B:移除列
var options = new ColumnOptions();
options.Store.Remove(StandardColumn.Properties);
options.Store.Remove(StandardColumn.MessageTemplate);
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer(connectionString, tableNameB, columnOptions: options, autoCreateSqlTable: true)
.CreateLogger();
Write();
//C:添加自定义列
options = new ColumnOptions();
options.AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP" },
new SqlColumn { DataType = SqlDbType.NVarChar, DataLength =-1, ColumnName = "IP2" }
};
Log.Logger = new LoggerConfiguration()
.Enrich.WithProperty("IP", "8.8.8.8")
.Enrich.WithProperty("IP2", "9.9.9.9")
.WriteTo.MSSqlServer(connectionString, tableNameC, columnOptions: options, autoCreateSqlTable: true)
.CreateLogger();
Write();
Console.WriteLine("Hello World!");
}
catch (Exception ex )
{
throw;
}
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16535250.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
![](https://images.cnblogs.com/cnblogs_com/wml-it/2196906/o_230823011905_wxgzhss.png)