Proper way to constantly log to file

I am working on an app that will need a lot of logging. It's a completely offline system and the user wants all the logs to a file. What is the best way to handle this so that: 1. All the logs are written in the order that they are called 2. It won't freeze the app waiting for any of the writing to complete At first I tried just making every log call a fire and forget task, but I noticed some logs would be out of order. There can be hundreds of log calls every few seconds so I can't make it synchronous because it freezes the UI (WPF if that matters). Any tips or suggestions would be great.
9 Replies
SpReeD
SpReeD2mo ago
Use a logging framework like Serilog or NLog
Somgör from Human Resources
You could use an in memory database like SQLite since it can handle a lot of requests at the same time and then when the program closes you dump the log into a file sorted by timestamp Its unlikely the user will read the logs while they are being created, not that it's possible anyways
Nacho Man Randy Cabbage
Can't use any third party libraries unfortunately. They actually do want to read logs sometimes while the app is running. Reading up on blockingcollection now. Sounds like it may be what I want?
leowest
leowest2mo ago
I mean do u consider microsoft libraries as 3rd party? https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line that is not limited to console, u can use anywhere
Nacho Man Randy Cabbage
Microsoft libraries are typically fine. We essentially copied this already for setting the log level in a config file and formatting the messages and all that. Am I missing where it talks about the actual logging process itself? Oh wait just read this "Instead, synchronously add log messages to an in-memory queue and have a background worker pull the messages out of the queue to do the asynchronous work of pushing data to SQL Server."
Somgör from Human Resources
in this case you could dump the config in regular intervals for example every 15 seconds etc you either append the text or create temp files that merge into one later
Nacho Man Randy Cabbage
That can work. Just need to add something to write the last log if the app completely crashes.
Somgör from Human Resources
you can catch the event of the app closing then you have a short time frame to run code but i dont think you can really do anything if it really crashes