【问题标题】:Serilog RollingFileSerilog 滚动文件
【发布时间】:2015-11-13 11:59:23
【问题描述】:

我正在尝试将WriteTo.RollingFile 与 Serilog 一起使用,如下所示每天写入一个文件:

var log = new LoggerConfiguration().WriteTo.RollingFile(
                    @"F:\logs\log-{Date}.txt",
                    LogEventLevel.Debug).CreateLogger();
            log.Information("this is a log test");

但我在同一天获得了一个新的日志文件每个日志条目

如何将 Serilog 配置为每天写入一个新文件,以便每天拥有一个日志文件?


是否有任何归档过程可以删除超过 7 天的文件?

【问题讨论】:

  • 另外,您需要确保只配置一次日志,然后继续为所有消息重复使用相同的log 实例。 HTH!

标签: c# .net serilog


【解决方案1】:

试试下面:

 var log = new LoggerConfiguration()
          .MinimumLevel.Debug()
          .WriteTo.File(@"f:\log\log.txt", rollingInterval: RollingInterval.Day) 
          .CreateLogger();

日志文件名会自动为log-20150819.txt等,不需要指定日期,旧文件会按照retainedFileCountLimit清理——默认31个。

【讨论】:

  • 这解决了他的一个问题。另一个问题是我也有关于在同一天创建多个日志文件的问题。但是其中一个cmets把它钉在了头上。只配置一次并为所有消息使用相同的日志实例。我已经配置过一次,但我试图弄清楚如何在整个应用程序中使用它。如果我没有在每个类中进行配置,那么日志记录就会停止。这是由于我的经验不足。
  • WriteTo.RollingFile 现已弃用 阅读 Github 页面:github.com/serilog/serilog-sinks-rollingfile
  • 宁可使用 Log.Logger = new LoggerConfiguration()....... 这样你就有了一个全局句柄,你可以像这样使用它: Log.Information("Hello");或 Log.Error("这是一个错误");
【解决方案2】:

WriteTo.RollingFile 已弃用

自从发布答案后,RollingFile 方法不再可行,取而代之的是File 和滚动日志的选项。

现在必须使用支持滚动的标准Serilog.Sinks.File NuGet 包:

.WriteTo.File(path: @"e:\logs\skilliam.log", 
              rollingInterval: RollingInterval.Day,
              rollOnFileSizeLimit: true, 
              fileSizeLimitBytes: 123456);

【讨论】:

  • 它现在在Serilog.Sinks.RollingFile 中(似乎没有rollingInterval: RollingInterval.Day)。
  • @YahooSerious,但是你如何定义滚动周期?
  • 根据github.com/serilog/serilog-sinks-rollingfile,您使用{Date}{Hour}{HalfHour}。但他们也声明它已被弃用。所以我再次尝试了你的代码,它现在可以工作了。我想知道为什么它第一次对我不起作用。也许是另一个包/版本,或者我尝试了RollingFile 而不是File?嗯,我猜那是“桥下的水”。
【解决方案3】:

这是一种在 asp.net MVC 4/5 应用程序中将 Serilog 与 web.config 一起使用的方法。

在您的 web.config 中添加以下内容:

<add key="serilog:minimum-level" value="Information" />
<add key="serilog:minimum-level:override:Microsoft" value="Information" />
<add key="serilog:minimum-level:override:System" value="Information" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:RollingFile.pathFormat" value="./Logs/log-{Date}.txt" />
<add key="serilog:write-to:RollingFile.outputTemplate" value="{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />

然后在 global.asax 的 Application_Start 中添加以下内容:

// Get application base directory
string basedir = AppDomain.CurrentDomain.BaseDirectory;

// Setup Serilog for logging
Log.Logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .WriteTo.RollingFile(basedir + "/Logs/log-{Date}.txt")
            .CreateLogger();

【讨论】:

    【解决方案4】:

    要使用同一个文件,你必须添加shared: true

    .WriteTo.RollingFile("log-{Date}.txt", shared: true)

    【讨论】:

      【解决方案5】:

      要启用多进程共享日志文件,请将 shared 设置为 true:

      在代码中

      .WriteTo.RollingFile("log-{Date}.txt", shared: true)
      

      或在 web.config 中

      <add key="serilog:write-to:RollingFile.shared" value="true" />
      

      【讨论】:

      • 我如何通过 appsetting.json 设置共享属性,你能提供一个示例吗.. 我试过这个,但它不起作用.. "Name": "RollingFile", "Args": { "pathFormat": "D:\\Log-{Date}.json", "shared": "true"
      【解决方案6】:

      作为后续行动,请确保您使用全局范围的“日志”实例。

      例子:

      Log.Information("Hello world");
      

      【讨论】:

        【解决方案7】:

        WriteTo.RollingFile 已弃用 -> 使用格式化程序

        如果使用文本格式化程序ITextFormatter,请注意path 的变量位置在使用File 时已切换到第二位。

        所以用格式化器来使用这个格式:

        var filepath = @"C:\Logs";
        ITextFormatter jsonFormatter = new Serilog.Formatting.Json.JsonFormatter(renderMessage: true);
        
        ...
        
        Log.Logger = new LoggerConfiguration()
                          ... // Enrichers etc...
                         .WriteTo.File(formatter: jsonFormatter,
                                       path: filepath,                            
                                       rollingInterval: RollingInterval.Day,
                                       rollOnFileSizeLimit: true, 
                                       fileSizeLimitBytes: 123456,
                                       shared: true)
                         .CreateLogger();
        

        【讨论】:

          【解决方案8】:

          我就是这样做的:

          private readonly Serilog.ILogger _logger; //= Log.ForContext( "Name", "Weather" );
          
          public WeatherForecastController() {
            string subPath = Path.Combine( DateTime.Now.ToString( "yyyy" ), DateTime.Now.ToString( "MM" ) ) + $"/{DateTime.Now.ToString("dd")}_Weather";
            _logger = Log.ForContext( "Name", subPath );
          }
          

            .UseSerilog( ( hostingContext, loggerConfiguration ) => loggerConfiguration
              .ReadFrom.Configuration( hostingContext.Configuration )
              .Enrich.FromLogContext()
              .WriteTo.Console()
              .WriteTo.Map(
                "Name",
                "Request",
                ( name, wt ) => {
                  if (name == "Request")
                    wt.RollingFile( Path.Combine( $"{hostingContext.Configuration["LogPath"]}/{{Date}}-{name}.txt" ) );
                  else
                    wt.File( $"{hostingContext.Configuration["LogPath"]}/{name}.txt" );
                } )
            );   
          

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多