Search code examples
c#loggingtracelistener

Nothing shows up in my log file


I am trying to create a logger that logs all stack trace to my text file, "log.txt". When I run this code, a blank log.txt document get created in the directory, but nothing is being written in the txt file.

My following code is the following:

public void Log()
    {
        // Create a file for output .txt.
        Stream debugFile = File.Create(@"C:\temp\log.txt");
        // create TextWriterTraceListener named "file"
        TextWriterTraceListener debugWriter = new TextWriterTraceListener(debugFile, "file");
        // add to debug listeners
        Debug.Listeners.Add(debugWriter);
        // set callstack to be shown
        Debug.Listeners["file"].TraceOutputOptions |= TraceOptions.Callstack;
        // set auto-flush
        Debug.AutoFlush = true;
        Debug.WriteLine("Message: " + Environment.StackTrace);
        debugFile.Close();
    }

Solution

  • Make sure that the 'Define DEBUG constant' checkbox is checked in your Project's Properties > Build section.

    It's basically just a defined constant, though Microsoft somewhat cryptically calls them 'Conditional Compilation Symbols'... VS does stuff depending on whether TRACE or DEBUG are defined (like allow writing out to debug or trace listeners). In this way, you can write all the debug helpers you want into your files, and as long as they are surrounded by #if and #endif, once you're ready to deploy your program simply don't define those constants, and the compiler will ignore (not compile) those sections of code.

    You can also define your own constants. Say you type into the Conditional Compilation Symbols box the following: "SENDLOGGING". In your code, you can

    private void Log()
    {
        #if LOCALLOGGING
        //write to a file 
        #elif SENDLOGGING
        //send yourself an email with relevant info
        #else
        //do some other stuff
        #endif
    }
    

    In this case, the middle section will run. Had you defined LOCALLOGGING, the first block would run.

    More reading: https://msdn.microsoft.com/en-us/library/0feaad6z.aspx