C
C#8h ago
Rodonies

Dependency Injection Logging: AddDebug() works but AddSerilog() doesn't.

Hi, I am using Microsoft.Extensions.DependencyInjection and Serilog I invoke the following on a serviceCollection:
serviceCollection.AddLogging(builder =>
{
LoggerConfiguration loggerConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(31));

builder.AddSerilog(loggerConfig.CreateLogger());
builder.AddDebug();
})
serviceCollection.AddLogging(builder =>
{
LoggerConfiguration loggerConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(31));

builder.AddSerilog(loggerConfig.CreateLogger());
builder.AddDebug();
})
This is how I get a logger from the constructor:
public MainViewModel(ILogger<MainViewModel> logger) {
_logger = logger;
_logger.LogDebug("{Message}", "INIT MainViewModel");
}
public MainViewModel(ILogger<MainViewModel> logger) {
_logger = logger;
_logger.LogDebug("{Message}", "INIT MainViewModel");
}
I see that message appear in the debug window but Serilog does not make the file, however if I change
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(31));
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(31));
to
.WriteTo.File("logs/log.txt");
.WriteTo.File("logs/log.txt");
Serilog actually creates the file, but it doesn't write anything to it, which makes me think I actually am using this correctly? I found something that says you need to convert the Serilog's logger to a Microsoft.Extensions.Logging.ILogger, but that solution is for ASP.NET and I'm not sure if it applies since that HostBuilder is not used in WPF
Stack Overflow
Serilog does not output logs into the txt file
Im using dotnet worker service (.net 5) I integrated serilog as well as enrichers and sinks. But for some reason I dont see any outputs into my files logs. Here is my appsettings.json { "
2 Replies
Jimmacle
Jimmacle7h ago
it seems wrong that you're trying to add 2 different logging services, if you want logging to the debug console that should be configured as a serilog sink and not as a separate logging service e.g. loggerConfig.WriteTo.Debug();
Rodonies
RodoniesOP6h ago
I primarily want a log file, but Serilog on it's own didn't work. nothing changes when I remove
builder.AddDebug();
builder.AddDebug();
I only added this line afterwards to see if the logger actually worked, since I couldn't get Serilog to work

Did you find this page helpful?