简体   繁体   English

Serilog - RollingFile Sink 不会根据日期和大小滚动文件

[英]Serilog - RollingFile Sink does not roll files based on date and size

I am using Serilog - RollingFile Sink, but it stores all data in a single file for a day.我正在使用 Serilog - RollingFile Sink,但它将所有数据存储在一个文件中一天。 In my application, 1 GB log is written in a day.在我的应用程序中,一天写入 1 GB 日志。 So I want to roll log file on the basis of date and size.所以我想根据日期和大小滚动日志文件。

How can I configure RollingFile Sink to roll files based on date and size?如何配置 RollingFile Sink 以根据日期和大小滚动文件?

Nowadays Serilog.Sinks.RollingFile package is deprecated in favor of Serilog.Sinks.File (see the github project readme intro).现在 Serilog.Sinks.RollingFile 包已被弃用,取而代之的是 Serilog.Sinks.File(参见 github 项目自述文件介绍)。 Serilog.Sinks.File package has been upgraded to support file rolling. Serilog.Sinks.File 包已升级以支持文件滚动。 You can use the following Serilog config to enable rolling both by time and size:您可以使用以下 Serilog 配置来启用按时间和大小滚动:

"Serilog": {
    "Using": ["Serilog.Sinks.File"],
    "MinimumLevel": "Debug",
    "WriteTo": [
        {
            "Name": "File",
            "Args": {
                "path": "logs/log.txt",
                "rollingInterval": "Day",
                "rollOnFileSizeLimit": true,
                "fileSizeLimitBytes": "512",
                "retainedFileCountLimit": 3,
                "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
            }
        }
    ]
  }

Then you will get something like this:然后你会得到这样的东西:

在此处输入图片说明

From the documentation :文档

To avoid bringing down apps with runaway disk usage the rolling file sink limits file size to 1GB by default.为了避免因磁盘使用失控而导致应用程序崩溃,滚动文件接收器默认将文件大小限制为 1GB。 The limit can be changed or removed using the fileSizeLimitBytes parameter.可以使用 fileSizeLimitBytes 参数更改或删除限制。

 .WriteTo.RollingFile("log-{Date}.txt", fileSizeLimitBytes: null)

The example shows removing the limit by setting it to null .该示例显示了通过将限制设置为null来移除限制。 In your case, set it to an appropriate size.在您的情况下,将其设置为适当的大小。

UPDATE更新

Yes, based on your comment I looked at the source code and it looks like the RollingFileSink's lowest unit of measure is a day so having more than one on the same day seems to be not supported.是的,根据您的评论,我查看了源代码,看起来 RollingFileSink 的最低度量单位是一天,因此似乎不支持在同一天使用多个度量单位。 However, and I didn't look closely, it looks like the OpenFile methods in RollingFileSink.cs does something with sequence numbers.然而,我没有仔细观察,看起来RollingFileSink.cs中的OpenFile方法对序列号做了一些事情。 You might want to take a peek and see what that code is doing.您可能想看一眼,看看代码在做什么。

I believe you're looking for this alternative implementation of the RollingFile sink:我相信您正在寻找 RollingFile 接收器的这种替代实现:

Serilog Rolling File Sink (alternative) Serilog 滚动文件接收器(替代)

This is a rolling file sink that allows you to specify roll over behaviour based on file size.这是一个滚动文件接收器,允许您根据文件大小指定滚动行为。 https://github.com/BedeGaming/sinks-rollingfile https://github.com/BedeGaming/sinks-rollingfile

In appsettings.json you should write something like that:在 appsettings.json 你应该写这样的东西:

{
"Serilog": {

  "Using": ["Serilog.Sinks.File"],
  "MinumumLevel": {
    "Default": "Error",
    "Override": {
      //"Microsoft": "Warning",
      //"System": "Warning",  
      "Microsoft.AspNetCore.Authentication": "Verbose",
      "WebApplicationLogger1.Startup": "Warning",
      "WebApplicationLogger1.Pages": "Warning"
    }
  },
  "WriteTo": [
    {
      "Name": "RollingFile",
      "Args": {
        "rollingInterval": "Day",  // --> THIS IS THAT YOU NEED
        "pathFormat": "C:\\Logfiles\\File-{Date}.log",
        "restrictedToMinimumLevel": "Warning"   
      }
     }
   ],
  }
}

The current version also implements rolling hourly.当前版本还实现了每小时滚动。 That might be another solution to your ploblem.这可能是您的问题的另一种解决方案。

{Hour} Creates a file per hour. {Hour} 每小时创建一个文件。 Filenames use the yyyyMMddHH format.文件名使用 yyyyMMddHH 格式。

like: .WriteTo.RollingFile("log-{Date}.Hour")像: .WriteTo.RollingFile("log-{Date}.Hour")

This is my solution这是我的解决方案

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" );
      } )
  );   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM