You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 Serilog配置:应用重启后日志追加至同一份每日文件

解决Serilog应用重启后重复生成当日日志文件的问题

问题核心是Serilog File Sink默认不允许进程重启后共享写入同一个文件,所以每次应用重启检测到当日日志文件已存在时,会自动生成带_001、_002后缀的新文件。要实现重启后追加到同一份每日日志,只需在文件接收器配置中开启共享写入模式。

修改配置步骤

在appsettings.json的Serilog File Sink参数里添加"shared": true即可,修改后的配置如下:

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "Using": [
      "Serilog.Enrichers.ClientInfo"
    ],
    "Enrich": [
      "WithClientIp",
      "WithClientAgent"
    ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "./logs/log-.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {ClientIp}{NewLine}{Exception}",
          "rollingInterval": "Day",
          "shared": true // 新增开启共享写入
        }
      },
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {ClientIp} <s:{SourceContext}>{NewLine}{Exception}"
        }
      }
    ]
  }

关键说明

  • shared: true会让Serilog以共享模式打开日志文件,允许进程重启后继续追加写入当日文件,避免生成带后缀的重复文件。
  • 你当前的retainedFileCountLimit默认值(31)完全满足保留一个月日志的需求,无需调整。
  • 确保应用进程对./logs文件夹拥有读写权限,避免因文件权限问题导致日志写入失败。

内容的提问来源于stack exchange,提问作者Sachihiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:47:10