0

I am trying to implement a class for logging that utilizes System.Diagnostics.Trace. I want to control when I want to write/flush data to file (listeners) so I want to disable AutoFlush = False but since I am using static class, I wonder how I am supposed to flush all remaining data such that I will not lose any pending logs to be written to file when the app (holding the Trace class) is closed instantly.

Please advise.

Below is a snippet of my class.


namespace App
{
    public class Trace 
    {   
        private Trace()
        {
            // prevent construction
        }

        Timer timer;

        private timer_Elapsed()
        {
            // Flush all pending lines to log
            System.Diagnostics.Trace.Flush()
        }

        static public void Initialize()
        {
            // Init
            System.Diagnostics.Trace.Listeners.Add( Listener );
            System.Diagnostics.Trace.AutoFlush = false;
        }

        static void Log(string str)
        {
            System.Diagnostics.Trace.WriteLine("str");
        }
    }
}
junPac
  • 101
  • 10
  • If this is an asp.net application you could use the "Application_End" event to make sure that the trace is flushed. – Emil Lundin Dec 10 '14 at 07:43
  • 1
    For other app types, see this link: http://stackoverflow.com/questions/1119841/net-console-application-exit-event – Emil Lundin Dec 10 '14 at 07:45
  • Thanks @EmilLundin. I am actually using some kind of `service` type application running 24x7 but during a shutdown, the possibility of losing data is possible if the flush interval is low. Is a console app technically the same as a `service`? – junPac Dec 10 '14 at 08:14
  • I would think that you can use the same approach for a service. Please note that the event won't be fired in case of a brute-force exit such as a power off. – Emil Lundin Dec 10 '14 at 08:33

0 Answers0