I am developing an application in C# and my current logging creates a StreamWriter and a FileStream at the beginning of the program like so:

//Activate Logging
try
{
    streamer = new FileStream("filepath and name", FileMode.OpenOrCreate, FileAccess.Write);
    writer = new StreamWriter(streamer);
}

There are a few events happening prior to creating this log file, as I use some parameters that need to be parsed from the arguments to create the file name, and so I am running into two issues

  1. If an error occurs before this file is created, I create another file called "crashlog", which logs the error itself. However, this file is sometimes empty.

  2. If an unhandled error occurs, even if the original logfile is created, that file is empty.

This leads me to believe that the log gets dumped in it's entirety once the program exits and the stream/writer are closed. Is there a method or parameter I am overlooking that would allow to write to a file as things happen? This would help me figure out exactly where things crashed.

I thought of a way to do it, but I feel it is extremely inefficient, this is the process I have in mind

  1. Create a file with a randomly generated name and store it as a variable
  2. Once variables have been parsed, rename the file appropriately
  3. Every time I want to log something, open the file, add the new line, close the file
  4. If a crash happens, rename the file appropriately

3 Replies 3

You're manually reinventing the wheel. Use an establish logging framework that handles all of this. Serilog for example has file log sinks and literally has the exact behavior you want for handling logging before being fully setup.

You may want to call the StreamWriter Flush() method if your application is closing down before the StreamWriter is flushed. That said, I agree with @gilliduck, you would be better off using a logging frame work.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.flush?view=net-9.0#system-io-streamwriter-flush

IMHO use the generic host & logging framework. Then try to delay all other work that may fail until the host is actually starting.

The generic host has been carefully designed to separate host configuration and logging from the rest of the application, to reduce these chicken and egg problems.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.