Fork me on GitHub

Serilog

1,引用包

    <PackageReference Include="Serilog.Extensions.Hosting" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />

2,初始化

        static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .MinimumLevel.Override("ProjectService", LogEventLevel.Error)//当前log类型的输出等级为error
            .Enrich.With(new ThreadIdEnrichar())//新增ThreadId字段
            .Enrich.FromLogContext()
            .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} {ThreadId}] {Message}{NewLine}{Exception}")//设置格式
            //.WriteTo.Async(c => c.File("Log\\logs.txt", rollingInterval: RollingInterval))
            .WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} {ThreadId}] {Message}{NewLine}{Exception}")
            .CreateLogger();

            string[] s = new string[] { "1", "2" };
            Log.Information("{@s}", s);

            await CreateHostBuilder(args).RunConsoleAsync();
            Console.WriteLine("Hello World!");
        }
ThreadIdEnrichar
using Serilog.Core;
using Serilog.Events;
using System.Threading;

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

 

posted on 2020-12-25 17:58  *Hunter  阅读(174)  评论(0编辑  收藏  举报

导航

AmazingCounters.com