serilog / serilog-sinks-async

An asynchronous wrapper for Serilog sinks that logs on a background thread
Apache License 2.0
231 stars 30 forks source link

Not able to format file name with rollingInterval or outputTemplate #89

Closed camilojara17 closed 12 months ago

camilojara17 commented 1 year ago

When I try to include a rolling interval using a Serilog.Sinks.Async it doesn´t create the log file, therefore it doesn´t log.

Here is the logic that I´m trying to use:

using Serilog;

var logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Async(a => a
.File(
    "logs/log.txt",
    rollingInterval: RollingInterval.Day
))
.CreateLogger();

logger.Information("This message will be logged asynchronously in a file.");

Also, I tried to include only outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" and it doesn´t create the file name with the expected correct format.

bartelink commented 1 year ago

You're best off asking this sort of question on stack overflow - more eyes, quicker responses. Use the Console log to rule out basic things For the File log, get it working without Async first, then worry about wrapping it in Async As a rule, the Async Sink is very boring - it just channels work around, but does not of itself change much about how things work or don't work.

nblumhardt commented 1 year ago

A using statement should fix this:

using var logger = new LoggerConfiguration()

As Reuben said, SO will have deeper insight/advice if this isn't the issue.

camilojara17 commented 12 months ago

Thank you! It´s weird that I need to include the using statement (or flush the object) but it worked.

bartelink commented 12 months ago

Thank you! It´s weird that I need to include the using statement (or flush the object) but it worked.

FYI, the issue is that the Async Sink offloads log events to a background thread, and your program in most cases will exit before events percolate through and get emitted.

Doing a using has the effect of awaiting the closing/flushing of the tree of Sinks before your program stops running.

If you just used e.g. a Console sink, the log statement would generally feed synchronously all the way through.

For a File Sink, but really all sinks, an app should always wait for the sinks to drain - often you'll see that as a finally Log.CloseAndFlush() in standard examples.

(But I will confess I didn't have Nick's insight when I read your question!)