Search code examples
c#asp.net-core.net-coreloggingserilog

How to log exception in separate file from the normal logs?


I had this code in my program.cs

// Logging service Serilogs
builder.Logging.AddSerilog();
Log.Logger = new LoggerConfiguration()
    .WriteTo.File(
    path: "logs/log-.txt",
    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}{NewLine}",
    rollingInterval: RollingInterval.Day,
    restrictedToMinimumLevel: LogEventLevel.Information
    )
    .WriteTo.File(
                path: "logs/exceptions-.txt",
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}{NewLine}",
                rollingInterval: RollingInterval.Day,
                restrictedToMinimumLevel: LogEventLevel.Error // Log only errors and above
            ).CreateLogger();

I am getting two logs while error is occured. One is normal logs with excception logs in it and another one is with only exception.

Is there any flag or anything that can determine in which file I want to write the logs in?

I tried created a separate class for Exception i.e. ExceptionLogger.cs where I have defined the path for exception and used that in all of my classes But the logs are getting inserted into the same normal logs. This problem is occuring with dotnet core 6


Solution

  • You could configure serilog like below:

    Log.Logger = new LoggerConfiguration()
        .WriteTo.Logger(l => l
            .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
            .WriteTo.File(
                path: "information.txt"))
    
        .WriteTo.Logger(l => l
            .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
            .WriteTo.File(
                path: "error.txt"))
            .CreateLogger();
    
    Log.Information("test Information");
    Log.Error("test Error");