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

如何在appsettings.json中配置Serilog生成UTF-8-BOM编码日志文件?

Serilog配置UTF-8-BOM编码日志文件的解决方法

错误原因

直接配置"encoding": "utf-8"会触发InvalidOperationException: Type UTF8 was not found.错误,因为Serilog的配置系统无法通过这个字符串别名直接定位到对应的.NET编码类型,必须指定完整的编码类型定义及参数。

正确配置方式

要生成带BOM的UTF-8日志文件,需要指定System.Text.UTF8Encoding类型,并通过参数开启BOM输出。具体修改如下:

将原配置中的"encoding": "utf-8"替换为:

"encoding": {
  "type": "System.Text.UTF8Encoding, System.Private.CoreLib",
  "args": {
    "encoderShouldEmitUTF8Identifier": true
  }
}

完整配置示例

修改后的完整appsettings.json日志配置:

"WriteTo:Async": {
  "Name": "Async",
  "Args": {
    "configure": [
      {
        "Name": "File",
        "Args": {
          "path": "Logs/Log-.txt",
          "rollOnFileSizeLimit": true,
          "fileSizeLimitBytes": 5242880,
          "retainedFileCountLimit": 31,
          "rollingInterval": "Day",
          "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] ({ThreadID}) [{SourceContext}] {Message}{NewLine}{Exception}",
          "encoding": {
            "type": "System.Text.UTF8Encoding, System.Private.CoreLib",
            "args": {
              "encoderShouldEmitUTF8Identifier": true
            }
          },
          "formatter": {
            "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions"
          }
        }
      }
    ]
  }
}

注意事项

  • 若使用**.NET Framework**而非.NET Core/.NET 5+,需将System.Private.CoreLib替换为mscorlib。
  • encoderShouldEmitUTF8Identifier参数设为true时,会强制生成UTF-8 BOM;设为false则对应无BOM的UTF-8编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:39:59