nreco / logging

Generic file logger for .NET Core (FileLoggerProvider) with minimal dependencies
MIT License
296 stars 60 forks source link

Missing logs in .NET #44

Closed linusalnervik closed 2 years ago

linusalnervik commented 2 years ago

Hi. When logging with a .NET application at the end of the program, the last logging is not committed to the file. Could it be that the dispose method is not waiting for the writing to complete? Have also noticed that when creating a new file for logging, creating a log event, and then closing the console, only a empty file is created, with no logging included.

VitaliyMF commented 2 years ago

FileLoggerProvider implements IDispose, and normally it should be called on the app shut down. If you use Microsoft.Logging with DI container, it does that by default. If not, you might need to call LoggerFactory.Dispose explicitely on the app stop.

linusalnervik commented 2 years ago

Ok. Well we do use Microsoft.Logging with DI container. But shouldn't the filewriter thread of the event keep the main thread (that call the disposal due to ending) from closing?

Right now the garbage collection seems to close out the filewriter thread to early.

VitaliyMF commented 2 years ago

@linusalnervik I'm not aware about your .NET app specifics; normally FileLoggerProvider works in this way:

Hope this helps.

linusalnervik commented 2 years ago

Hi again. This code will sometimes only create an empty file (it's a bit flaky would say 50% of the times).

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var serviceProvider = new ServiceCollection()
           .AddLogging(loggingBuilder => {
               loggingBuilder.AddFile("app.log", append: true);
           }).BuildServiceProvider();

var logger = serviceProvider.GetService<ILoggerFactory>()
           .CreateLogger<Program>();
logger.LogInformation("Starting application");

When adding a wait in the end the logging row is always commited to the file

Thread.Sleep(2000);
VitaliyMF commented 2 years ago

Do you call serviceProvider.Dispose() when your program ends?

linusalnervik commented 2 years ago

Yee that was the issue.

Thanks for help