学习Serilog日志笔记

发布时间 2023-09-28 13:01:37作者: 汤小明软件|电脑|监控

     本学习笔记所有的.net 版本为6.0 

首先引包nuget包为:serilog 和serilog.aspnetcore

1、在控制台下使用日志:

    需要引入Serilog.Sinks.Console包

  然后在program.cs中写入以下语句:

   Log.Logger=new LogerConfiguration()

.MinimumLevel.Debug()

    .WriteTo.Console()

    .CreateLogger();

Log.Information("hello this is Serilog Log");

Log.CloseAndFlush(); //这句一定要写上

2、在文件中使用日志:

    需要引入Serilog.Sinks.File包

  然后在program.cs中写入以下语句:

   Log.Logger=new LogerConfiguration()

.MinimumLevel.Debug()

    .WriteTo.File("Log.txt",rollingInterval:RollingInterval.Day)

    .CreateLogger();

Log.Information("hello this is Serilog Log");

Log.CloseAndFlush(); //这句一定要写上

 3,基于文本的接收器模板

  .WriteTo.File("Log.txt",outputTemplate:"{

Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}" )     

4、.同时写入到控制台和文件
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File("log.txt")
    .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
    .CreateLogger();
 Log.CloseAndFlush();

5、丰富器是添加、删除或修改附加到日志事件的属性的简单组件。例如,这可用于将线程 ID 附加到每个事件。

class ThreadIdEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                "ThreadId", Thread.CurrentThread.ManagedThreadId));
    }
}
 

使用配置对象添加丰富器Enrich

Log.Logger = new LoggerConfiguration()
    .Enrich.With(new ThreadIdEnricher())
    .WriteTo.Console(
        outputTemplate: "{Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}")
    .CreateLogger();
 

上面的配置显示了如何在输出格式中使用丰富器添加的属性。

如果丰富的属性值在整个应用程序运行过程中保持不变,则WithProperty可以使用快捷方法来简化配置。

Log.Logger = new LoggerConfiguration()
    .Enrich.WithProperty("Version", "1.0.0")
    .WriteTo.Console()
    .CreateLogger();
 

丰富器及其附加的属性通常对于使用结构化存储的接收器更有用,可以在其中查看和过滤属性值。

可以通过过滤有选择地记录事件。过滤器只是 的谓词LogEvent,其中一些常见场景由该类处理Matching

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .Filter.ByExcluding(Matching.WithProperty<int>("Count", p => p < 10))
    .CreateLogger();

子记录器

有时,需要对接收器所看到的内容进行更精细的控制。为此,Serilog 允许完整的日志管道充当接收器。

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(...)
        .WriteTo.File("log.txt"))
    .CreateLogger();