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

C# ILoggerFactory部署后日志格式异常,如何自定义日志格式?

控制C# API日志格式的解决方案

部署后日志格式混乱、出现Logger[0]和多余换行,是因为默认控制台日志提供器的输出格式和VS调试环境不一致。要实现[hh:mm:ss:msec] info: Some message A的统一格式,直接通过自定义日志格式化逻辑就能解决,具体步骤如下:

方法一:自定义纯文本日志格式化器

在Program.cs中,在builder.Build()之前添加日志配置,替换默认的控制台输出格式:

// 先配置日志,再构建应用
builder.Logging.ClearProviders(); // 清除默认日志提供器(如果需要完全自定义)
// 保留VS调试窗口的日志输出(可选)
builder.Logging.AddDebug();
// 添加自定义格式的控制台日志提供器
builder.Logging.AddConsole(options =>
{
    options.FormatterName = "customTextFormatter";
    options.Formatters.Add(new CustomTextConsoleFormatter(new CustomTextConsoleFormatterOptions()));
});

// 自定义纯文本日志格式化类
public class CustomTextConsoleFormatter : ConsoleFormatter
{
    private readonly CustomTextConsoleFormatterOptions _options;

    public CustomTextConsoleFormatter(CustomTextConsoleFormatterOptions options) : base("customTextFormatter")
    {
        _options = options;
    }

    public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter)
    {
        // 格式化时间为 [时:分:秒:毫秒] 格式
        var timeStamp = DateTime.Now.ToString("[HH:mm:ss:fff]");
        // 将日志级别转为小写(info/warn/error等)
        var logLevel = logEntry.LogLevel.ToString().ToLower();
        // 渲染日志消息
        var message = logEntry.Formatter(logEntry.State, logEntry.Exception);

        // 拼接成目标格式并输出,无多余换行
        textWriter.Write($"{timeStamp} {logLevel}: {message}{Environment.NewLine}");
    }
}

// 自定义格式化选项类(后续可扩展配置)
public class CustomTextConsoleFormatterOptions : ConsoleFormatterOptions
{
}

配置完成后,你原来的日志代码无需修改,输出就会变成指定的统一格式,同时去掉了Logger[0]这类无用信息和多余换行。

方法二:用内置JSON格式化器实现紧凑输出(可选)

如果接受JSON格式的日志,也可以用内置的JsonConsoleFormatter配置紧凑输出,去掉冗余字段:

builder.Logging.AddConsole(options =>
{
    options.FormatterName = "json";
    options.Formatters.Add(new JsonConsoleFormatter(new JsonConsoleFormatterOptions
    {
        TimestampFormat = "[HH:mm:ss:fff]",
        IncludeScopes = false,
        JsonWriterOptions = new System.Text.Json.JsonWriterOptions
        {
            Indented = false // 关闭缩进,去掉多余换行
        }
    }));
});

关键注意点

  • 日志配置必须放在builder.Build()之前,否则服务初始化后配置不会生效。
  • 如果不需要清除所有默认提供器,别调用ClearProviders(),避免丢失VS调试日志或其他必要输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:25:07