I have a lot of code where I use System.Diagnostics.Trace. I want to save all messages to file using ILogger, nlog. How I can do it?
You could implement your own TraceListener, which would look something similar to this
// https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracelistener?view=netframework-4.7.2
public class LoggerTraceListener : TraceListener
{
private readonly ILogger _logger;
public LoggerTraceListener(ILogger logger) {
_logger = logger;
}
public override void Write(string message)
{
_logger.LogInformation(message);
}
public override void WriteLine(string message)
{
_logger.LogInformation(message);
}
}
And then, in the Startup, you could register that listener
public class Startup
{
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
var logger = app.ApplicationServices.GetService<ILogger<Startup>>();
//https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/how-to-create-and-initialize-trace-listeners#to-create-and-use-a-trace-listener-in-code
Trace.Listeners.Add(new LoggerTraceListener(logger));
}
}
This would output to an ILogger, you could configure your logger factory to output to a file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With