关于c#:Serilog RollingFile

Serilog RollingFile

我正在尝试使用带有Serilog的WriteTo.RollingFile,如下所示:

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

我的理解是,该日志文件将根据日期创建和命名,并且每天都会写入一个新文件,但是我在同一天为每个日志条目获取了一个新的日志文件!
如何配置Serilog每天写入一个新文件,因此理想情况下每天我只有一个日志文件?

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


请尝试以下方法:

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

日志文件名将自动为log-20150819.txt等。您无需指定日期。旧文件将按照reservedFileCountLimit进行清理-默认值为31。


现在在2018年,标准的Serilog.Sinks.File NuGet软件包支持滚动:

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


要使用相同的文件,必须添加shared: true

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


这是在asp.net MVC 4/5应用程序中通过web.config使用Serilog的方法。

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

1
 

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

1
2
3
4
5
6
7
8
// 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();

作为后续操作,请确保您随后使用全局范围内的"日志"实例。

例:

1
Log.Information("Hello world");

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

在代码中

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

或在web.config中

1
 


这是我的方法:

1
2
3
4
5
6
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 );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  .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" );
      } )
  );