.net Serilog滚动文件

vnjpjtjt  于 2023-02-17  发布在  .NET
关注(0)|答案(9)|浏览(240)

我尝试使用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天以上的文件?

332nm8kg

332nm8kg1#

请尝试以下内容:

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

日志文件名将自动为log-20150819.txt等。您不需要指定日期。旧文件将根据retainedFileCountLimit(默认值为31)进行清理。

lkaoscv7

lkaoscv72#

写入.滚动文件已弃用

由于发布了答案,方法RollingFile不再可行,并替换为File和滚动日志的选项。
现在必须使用支持滚动的标准Serilog.Sinks.File NuGet包:

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

bybem2ql3#

下面是在www.example.com MVC 4/5应用程序中使用Serilog和web.config的方法asp.net。
在您的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();
wko9yo5t

wko9yo5t4#

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

用密码

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

或在web.config中

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

ilmyapht5#

要使用同一文件,必须添加shared: true
. WriteTo.滚动文件("日志-{日期}. txt",共享:正确)

m1m5dgzv

m1m5dgzv6#

作为此操作的后续操作,请确保随后使用全局范围的"Log"示例。
示例:

Log.Information("Hello world");
gg58donl

gg58donl7#

WriteTo.RollingFile已弃用-〉带格式设置程序

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

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();
hkmswyz6

hkmswyz68#

首先,你需要加上这些金块:

<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
        <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
        <PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
        <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
        <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
        <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />

比设置你的serilog在appsettings.json:

"Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File"
    ],
    "MinimumLevel": {
      "Default": "Information"
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "Path": "../Logs/MyLog-.json",
          "RollingInterval": "Day",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      },
      {
        "Name": "File",
        "Args": {
          "Path": "../Logs/MyLog-.log",
          "RollingInterval": "Day",
          "OutputTemplate": "[({Component}|{MachineName}|{ThreadId}) {Timestamp:G} [{Level:u3}]{Message:lj}{NewLine}{Exception} ]"
        }
      }
    ]
  }

那么您需要在C#代码中添加此配置。

var _logger = new LoggerConfiguration()
            .ReadFrom
            .Configuration(configuration)
            .Enrich
            .FromLogContext()
            .CreateLogger();
        services.AddLogging(logBuilder => logBuilder.AddSerilog(_logger));

configuration is an instance of IConfiguration, u will find builder.Configuration
services --> builder.Services
monwx1rj

monwx1rj9#

我是这样做的:

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

相关问题