C# Microsoft.Extensions.Logging how to redirect output to a specific file?

Viewed 33

I am using Microsoft.Extensions.Logging to output some data and wondering if I could redirect output to a specific file rather than the console. Here is my code:

  var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
                        .SetMinimumLevel(LogLevel.Trace).AddConsole());

  ILogger logger = loggerFactory.CreateLogger<DataLogger>();
  string path = GenerateFilePath();
  logger.LogInformation("DataLogger is initialized.");
  // todo: redirect output to path.

Is there a way I can redirect my output to the file path?

1 Answers

As said in the comments, your best bet is serilog

<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />

Add the service...

WebApplicationBuilder builder;
// create configure etc etc

builder.Services.AddLogging(logbuilder =>
    logbuilder.AddFile(builder.Configuration.GetSection("FileLogging"))
);

... and this section to yout appsettings.json

    "FileLogging": {
        "PathFormat": "logs/myapp.{Date}.log",
        "RetainedFileCountLimit": 69,
        "LogLevel": {
            "Default": "Warning",
            "MyNamespace": "Trace",
            "Microsoft": "Error"
        }
    },

you could configure everything as a delegate in AddLogging but i strongly suggest to add it to your configuration file.

for more info, it has it's own tag on SO https://stackoverflow.com/questions/tagged/serilog

Related