【问题标题】:How to use separate logs file for each service in .net core如何为 .net 核心中的每个服务使用单独的日志文件
【发布时间】:2025-12-19 07:40:12
【问题描述】:

我正在尝试使用 .net 核心记录每个服务的错误和信息。如何使用单独的文件进行日志记录。

目前我正在使用一个文件来记录所有错误和信息。

这是我的 Program.cs 和 Startup.cs

// Program.cs

public static void Main(string[] args)
        {
            CreateWebHostBuilder(args)
                .ConfigureLogging((hostingContext, logging) =>
                {
                    // Requires `using Microsoft.Extensions.Logging;`
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                    logging.AddEventSourceLogger();
                })
                .Build()
                .Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                });


// Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddFile("Logs/SmsDomeLogs-{Date}.txt");
            //.........
        }

【问题讨论】:

  • .NET Core 的日志记录没有任何文件提供程序。 AddFile 来自哪里?你在使用 Serilog 吗?
  • 是的,我正在使用 serilog。

标签: c# .net-core .net-core-logging


【解决方案1】:

解决方法的一个想法可能是创建一个自定义记录器,它将数据写入文件,并且您可以创建文件名以包含来自您的服务的某种自定义字符串。我也在用这种方式。例如:

private static string logFilePath;
private static readonly object _lock = new object();

public static void log(string serviceId, string className, string error, Exception exception) {
    string toLog = $"{className}: {error}";
    lock (_lock) {
        if (string.IsNullOrEmpty(logFilePath)) {
            string fileName = $"log-{DateTime.Now.Month}-{DateTime.Now.Day}-{serviceId}.log"; // you can also date if you want
            logFilePath = Path.Combine(<path to save>, fileName);
            if (!File.Exists(logFilePath)) {
                // create the file
            }
        }
        if (exception != null) { // you can log exceptions and debug messages too
            toLog += Environment.NewLine + exception.ToString();
        }

        toLog = $"{<you can add here date if you want>} - {toLog}";
        using (StreamWriter writer = File.AppendText(logFilePath)) {
            writer.WriteLine(toLog);
        }
    }
}

当然,您可以改进自己想要的方式,添加日志级别等。

【讨论】:

  • 问题不在于如何写入文件。这是如何配置 Serilog 以写入每个类别的不同文件。写入日志远比简单地向文件追加一行要复杂得多。
最近更新 更多