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

如何移除C#日志输出中的Program[0]标识?

移除日志输出中的Program[0]

关于Program[0]的含义

  • Program:是你通过ILogger<Program>创建日志器时指定的日志类别,默认以泛型类型的名称作为类别标识。
  • [0]:是日志的事件ID,调用LogInformation等方法未显式指定事件ID时,会使用默认值0。

移除方法:自定义控制台日志格式

你可以修改AddSimpleConsole的配置,自定义日志输出格式,剔除类别和事件ID部分,有两种实现方式:

方式1:使用自定义格式化委托(灵活度高)

using Microsoft.Extensions.Logging;

using ILoggerFactory loggerFactory =
    LoggerFactory.Create(builder =>
        builder.AddSimpleConsole(options =>
        {
            options.IncludeScopes = true;
            options.SingleLine = true;
            options.TimestampFormat = "HH:mm:ss ";
            // 自定义格式,仅保留时间戳、日志级别和消息
            options.Format = (logEntry, formatterOptions) =>
            {
                return $"{logEntry.Timestamp.ToString(formatterOptions.TimestampFormat)}{logEntry.LogLevel}: {logEntry.Message}";
            };
        }));

ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

logger.LogInformation("Hello World!");
logger.LogInformation("Logs contain timestamp and log level.");
logger.LogInformation("Each log message is fit in a single line.");

方式2:直接指定预定义格式字符串(更简洁)

using Microsoft.Extensions.Logging;

using ILoggerFactory loggerFactory =
    LoggerFactory.Create(builder =>
        builder.AddSimpleConsole(options =>
        {
            options.IncludeScopes = true;
            options.SingleLine = true;
            // 直接定义输出格式,去掉类别和事件ID占位符
            options.LogEntryFormat = "{Timestamp:HH:mm:ss} {Level}: {Message}";
        }));

ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

logger.LogInformation("Hello World!");
logger.LogInformation("Logs contain timestamp and log level.");
logger.LogInformation("Each log message is fit in a single line.");

修改后输出示例:

10:01:30 info: Hello World!
10:01:30 info: Logs contain timestamp and log level.
10:01:30 info: Each log message is fit in a single line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:42:16