Reputation: 161
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?
Upvotes: 4
Views: 2056
Reputation: 176
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.
Upvotes: 5
Reputation: 239300
You can't. However, if you work the other way around, i.e. adding the Trace provider to Microsoft.Extensions.Logging, and then logging with ILogger
. messages will go out to Trace, and any other logging you have setup.
If you're trying to capture logging done by the framework, .NET Core already uses Microsoft.Extensions.Logging. You simply need to change your log level appropriately so it captures Debug and Trace levels, in addition to the default of Info or higher. Additionally, if you're only interested in logging from certain components, you can specify log levels and providers by namespace. The docs have all the information you need there.
Upvotes: 1