Serilog 日志使用配置文件加载

发布时间:2023年12月20日
{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Settings.Configuration" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Warning",
        "System": "Warning",
        "Microsoft": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "restrictedToMinimumLevel": "Information",
          "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/trace/trace-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Verbose"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/debug/debug-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Debug"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/info/info-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/warning/warning-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Warning"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/error/error-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Error"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "{CurrentDirectory}/logs/fatal/fatal-.log",
          "rollingInterval": "Day",
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}",
          "restrictedToMinimumLevel": "Fatal"
        }
      }
    ],
    "Filter": [
      {
        "Name": "With",
        "Args": {
          "filter": {
            "type": "SpaceNation.GameServer.Utility.Serilog.CustomFilter, spacenation.game.application.server",
            "levelFilter": "Verbose"
          }
        }
      }
    ],
    "LogFilterKeys": [
      "Orleans",
      "Microsoft.AspNetCore",
      "Microsoft.Hosting",
      "Microsoft.Extensions"
    ]
  }
}

我是单独添加了一个配置文件?serilogsettings.json

2,加载配置文件
?

   private static string CurrentDirectory { get; } = AppDomain.CurrentDomain.BaseDirectory ?? throw new Exception("无法获取当前路径");

   /// <summary>
   /// 
   /// </summary>
   /// <returns></returns>
   public static IConfigurationRoot GetAndSetConfiguration()
   {
       var s = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")?.Replace(".", string.Empty);
       s = string.IsNullOrEmpty(s) ? s : $".{s}";
       string AppSettings = $"appsettings{s}.json";
       string SerilogSettings = $"serilogsettings{s}.json";

       Console.WriteLine($"当前程序集所在路径:{CurrentDirectory}");
       Console.WriteLine($"当前应用配置:{AppSettings}");

       var configuration = new ConfigurationBuilder()
           .SetBasePath(CurrentDirectory)
           .AddJsonFile($"activity.json", true, reloadOnChange: true)
           .AddJsonFile(AppSettings, false, reloadOnChange: true)
           .AddJsonFile(SerilogSettings, false, reloadOnChange: true)
           .Build();

       return configuration;
   }

3、使用配置文件
?

 public static WebApplicationBuilder AddGameServerlog(this WebApplicationBuilder builder, IConfigurationRoot configuration)
 {
     builder.Services.AddLogging(bulid =>
     {
         string currentDirectory = Directory.GetCurrentDirectory();
         var writeToSection = configuration.GetSection("Serilog:WriteTo");
         foreach (var section in writeToSection.GetChildren())
         {
             var argsSection = section.GetSection("Args");
             var pathValue = argsSection["path"];
             if (!string.IsNullOrEmpty(pathValue))
             {
                 var replacedPathValue = pathValue.Replace("{CurrentDirectory}", currentDirectory);
                 argsSection["path"] = replacedPathValue;
             }
         }

         Log.Logger = new LoggerConfiguration()
             .ReadFrom.Configuration(configuration)
             //.Enrich.WithThreadId()
             .CreateLogger();

         builder.Host.UseSerilog();
     });

     return builder;
 }

4,根据配置文件需要增加一个过滤类

using Serilog.Core;
using Serilog.Events;
using SpaceNation.Game.GameServer.Utility;
namespace SpaceNation.GameServer.Utility.Serilog
{
    /// <summary>
    /// 自定义过滤
    /// </summary>
    public class CustomFilter : ILogEventFilter
    {
        private readonly LogEventLevel _levelFilter;
        /// <summary>
        /// 过滤字符
        /// </summary>
        private readonly HashSet<string> _filteredSources;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="levelFilter"></param>
        public CustomFilter(LogEventLevel levelFilter = LogEventLevel.Information)
        {
            _levelFilter = levelFilter;
            _filteredSources = GetFilteredSourcesFromConfiguration();
        }

        private HashSet<string> GetFilteredSourcesFromConfiguration()
        {
            var configuration = GameServerUtility.GetAndSetConfiguration();
            var filteredSources = configuration.GetSection("Serilog:LogFilterKeys")
                .Get<string[]>();
            if (filteredSources is null)
            {
                return [];
            }
            return new HashSet<string>(filteredSources);
        }

        /// <summary>
        /// 过滤是否打印相关日志
        /// </summary>
        /// <param name="logEvent"></param>
        /// <returns></returns>
        public bool IsEnabled(LogEvent logEvent)
        {
            if (logEvent.Properties.ContainsKey("SourceContext") && _filteredSources.Count > 0)
            {
                var sourceContext = logEvent.Properties["SourceContext"].ToString();
                foreach (var filteredSource in _filteredSources)
                {
                    if (sourceContext.Contains(filteredSource))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}

最后。如果不喜欢使用配置文件就使用如下代码也可以,记得取消注释

/ <summary>
/ 日志
/ </summary>
/ <param name="builder"></param>
/ <param name="configuration"></param>
/ <returns></returns>
//public static WebApplicationBuilder AddGameServerlog(this WebApplicationBuilder builder, IConfigurationRoot configuration)
//{
//    var currdir = Directory.GetCurrentDirectory();
//    string infoPath = currdir + @"/logs/info/info-.log"; ;
//    string waringPath = currdir + @"/logs/waring/waring-.log";
//    string errorPath = currdir + @"/logs/error/error-.log";
//    string fatalPath = currdir + @"/logs/fatal/fatal-.log";
//    string debugPath = currdir + @"/logs/debug/debug-.log";
//    string tracePath = currdir + @"/logs/trace/trace-.log";
//    const string kLogOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ThreadId} {Level:u3}] {Message:lj} {NewLine}{Exception}";
//    //string template = "{NewLine}时间:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}等级:{Level}{NewLine}来源:{SourceContext}{NewLine}具体消息:{Message}{NewLine}{Exception}";
//    builder.Services.AddLogging(bulid =>
//    {
//        Log.Logger = new LoggerConfiguration()
//       .ReadFrom.Configuration(configuration)
//       .Enrich.WithThreadId()
//       .WriteTo.Console(LogEventLevel.Information)
//       .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Verbose)
//       .WriteTo.Async(congfig => congfig.File(
//                  tracePath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,//默認1GB
//                  restrictedToMinimumLevel: LogEventLevel.Verbose,
//                  rollOnFileSizeLimit: true,//超過文件大小時 自動創建新文件  
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//       .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Debug)
//       .WriteTo.Async(congfig => congfig.File(
//                  debugPath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,//默認1GB
//                  restrictedToMinimumLevel: LogEventLevel.Debug,
//                  rollOnFileSizeLimit: true,//超過文件大小時 自動創建新文件  
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//       //----------------------Information-------------------------------------------------------------------
//       .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Information)
//       .WriteTo.Async(congfig => congfig.File(
//                  infoPath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,//默認1GB
//                  rollOnFileSizeLimit: true,//超過文件大小時 自動創建新文件  
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//        //--------------------------Warning---------------------------------------------------------
//        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Warning)
//        .WriteTo.Async(congfig => congfig.File(
//                  waringPath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,
//                  rollOnFileSizeLimit: true,
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//       //-------------------------------Error----------------------------------------------------
//       .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Error).
//        WriteTo.Async(congfig => congfig.File(
//                  errorPath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,
//                  rollOnFileSizeLimit: true,
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//        //-------------------------------Fatal----------------------------------------------------
//        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Fatal)
//        .WriteTo.Async(congfig => congfig.File(
//                  fatalPath,
//                  rollingInterval: RollingInterval.Day,
//                  fileSizeLimitBytes: 50 * 1024 * 1024,
//                  rollOnFileSizeLimit: true,
//                  shared: true,
//                  outputTemplate: kLogOutputTemplate)
//        ))
//        //-----------------------------------------------------------------------------------
//       .CreateLogger();
//        builder.Host.UseSerilog();//这样不使用配置文件,使用AddLogging
//        //以下使用配置文件配置
//        //builder.Host.UseSerilog(
//        //    (context, logger) =>
//        //{
//        //    logger.ReadFrom.Configuration(context.Configuration);
//        //    logger.Enrich.FromLogContext();

//        //}
//        //);
//        //return builder;
//    });
//    return builder;
//}

文章来源:https://blog.csdn.net/Accpdaiyekun/article/details/135112080
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。