How to use separate logs file for each service in .net core

866 Views Asked by At

I am trying to Log errors and information for each service using .net core. How can i use separate files for logging.

Currently i am using one file for log all errors and information.

Here is my Program.cs and 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");
            //.........
        }
1

There are 1 best solutions below

1
On

An idea as a workaround could be to create a custom logger which writes the data to file, and you can create the file name to contain some kind of custom string from your services. I'm using this way, too. For ex.:

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);
        }
    }
}

And of course, you can improve how you want, add log levels, etc.