Click here to Skip to main content
Click here to Skip to main content

Errors in XML Log with C#/.NET

, 23 Oct 2002
Rate this:
Please Sign up or sign in to vote.
How to write all your errors when using Console.Error to an XML file.
<!-- Download Links --> <!-- Add the rest of your HTML here -->


Like other programmers I use a lot of try...catch statements in my code to catch exceptions, help debug, and avoid crashs. For that reason, I put a lot of Console.Error.WriteLine(...) in my catch blocks to keep a trace of the exceptions that occured. But when I release an app, even if exceptions should not happen anymore, it is always useful to have some kind of system to keep a trace of raised exceptions. The following code demonstrates a solution to keep a trace of those exceptions in a XML file.

The ErrorLogWriter class

This class inherits from the standard System.IO.TextWriter class. Subclassing TextWriter allows us to use our custom ErrorLogWriter class with Console.Error.
The trick is to create an ErrorLogWriter instance and then call Console.SetOut(...) with this instance as a parameter.
Then every Console.Error.WriteLine(...) call will be redirected to our ErrorLogWriter instance and a XML entry added in the file.
I tried to keep the code as simple as possible. So many features can be added, like handling more TextWriter.Write methods or providing even more informations in the ErrorLogWriter.WriteLine function.
To give this article some additional value, I also gave a way to get the calling class and method using the stack trace and reflection. I also added an attribute to the ErrorLogWriter.WriteLine function to synchronize it in multi-threaded programs (equivalent to the lock(this) keyword).

using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace ErrorLogger.Utility{
    /// <summary>
    /// ErrorLogWriter class
    /// </summary>
    public class ErrorLogWriter:TextWriter{
        // Variables
        private bool Disposed;
        private XmlTextWriter Writer;

        // Constructor
        public ErrorLogWriter(string FilePath){
            Writer=new XmlTextWriter(FilePath,Encoding.Unicode);

            // Write header

        // Destructor (equivalent to Finalize() without the need to call base.Finalize())

        // Free resources immediately
        protected override void Dispose(bool Disposing){
                // Close file
                // Disposed
                // Parent disposing

        // Close the file
        public override void Close(){
            // Write footer
            // Free resources

        // Implement Encoding() method from TextWriter
        public override Encoding Encoding{

        // Implement WriteLine() method from TextWriter (remove MethodImpl attribute for single-threaded app)
        // Use stack trace and reflection to get the calling class and method
        public override void WriteLine(string Txt){
            Writer.WriteString(new StackTrace().GetFrame(2).GetMethod().ReflectedType.FullName);
            Writer.WriteString(new StackTrace().GetFrame(2).GetMethod().ToString());

The test class

Here is an example of how to use the ErrorLogWriter class. Of course, all this code is available in the zip file.

using System;
using System.IO;
using ErrorLogger.Utility;

namespace ErrorLogger{
    /// <summary>
    /// Testing class
    /// </summary>
    class Test{
        /// <summary>
        /// Main loop
        /// </summary>
        static void Main(string[] args){
            // Here is the magic (file in .exe current directory)
            ErrorLogWriter Err=new ErrorLogWriter(Directory.GetCurrentDirectory()+@"\Error.xml");

            // Testing
            Console.Error.WriteLine("Here is my first error !");
            Console.Error.WriteLine("I should write this inside a catch(exception) statement...");
            // Inside another function

            // Close error file

            // Wait for key
            Console.Out.WriteLine("Error file created. Press a key...");

        // Just for the test
        private static void newFunction(){
            Console.Error.WriteLine("Look ! I am inside a function !");


I hope this article will help some people and will be useful for somebody.
Here you have basic concepts to understand how to subclass the TextWriter class, how to redirect the standard Console.Error stream and some tips about reflection and stack trace.
It is also worth to add that you can customize this code to redirect other streams like Console.In or Console.Out.

Happy Coding !!!


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Software Developer (Senior) Siliconz Ltd
New Zealand New Zealand
Richard Lopes
Just Programmer

Comments and Discussions

Generallog4net PinmemberJonathan de Halleux14-May-03 2:48 
GeneralRe: log4net PinmemberGriffonRL14-May-03 3:23 
GeneralSuggestion for improvement PinmemberAnthony_Yio16-Jan-03 17:20 
GeneralRe: Suggestion for improvement PinmemberAnthony_Yio16-Jan-03 17:26 
GeneralRe: Suggestion for improvement PinmemberGriffonRL16-Jan-03 23:16 
GeneralLogging to XML PinmemberKiliman26-Dec-02 10:24 
GeneralRe: Logging to XML PinmemberGriffonRL26-Dec-02 23:26 
GeneralRe: Logging to XML PinmemberHeath Stewart21-Jan-03 5:42 
GeneralRe: Logging to XML PinmemberGriffonRL22-Jan-03 2:22 
GeneralRe: Logging to XML PinmemberHeath Stewart22-Jan-03 3:13 
GeneralRe: Logging to XML PinmemberHeath Stewart22-Jan-03 3:19 
GeneralRe: Logging to XML PinmemberGriffonRL22-Jan-03 3:29 
GeneralRe: Logging to XML PinmemberHeath Stewart22-Jan-03 3:41 
GeneralRe: Logging to XML PinmemberGriffonRL22-Jan-03 4:39 
GeneralRe: Logging to XML PinmemberHeath Stewart22-Jan-03 4:51 
We'll implement simple RLE compression for this first version and implement something closer to zlib later. Basically, we have to override the formatter sink and just run the bytes through a compressor. There are several compression libraries out there, but since one needs to sit on the client, I don't want throughput wasted by excessive functionality we don't need. We just need the compression algorithm, not file support, stream support, MIME encoded base64 support, etc. etc. By simply overriding the binary formatter, we can hypothetically call the base classes primary methods then just run the return through an algorithm. Almost like inserting another sink *after* the formatter.
"Well, I wouldn't say I've been missing it, Bob." - Peter Gibbons
GeneralRe: Logging to XML PinmemberGriffonRL22-Jan-03 5:08 
GeneralRe: Logging to XML PinmemberHeath Stewart22-Jan-03 5:18 
GeneralRe: Logging to XML PinmemberGriffonRL22-Jan-03 4:25 
GeneralRe: Logging to XML Pinsussjustinj22-Feb-03 17:21 
GeneralRe: Logging to XML PinmemberGriffonRL23-Feb-03 21:54 
GeneralRe: Logging to XML Pinmemberltphu200117-May-04 15:27 
GeneralRe: Logging to XML Pinmemberreborn_zhang26-Nov-09 4:18 
GeneralErrorLogger Pinmemberxptom9-Dec-02 11:10 
GeneralRe: ErrorLogger PinmemberGriffonRL9-Dec-02 22:59 
GeneralHere is an example output PinmemberGriffonRL25-Oct-02 4:24 
GeneralRe: Here is an example output PinmemberDeepak Kumar Vasudevan7-Nov-02 4:42 
GeneralRe: Here is an example output PinmemberGriffonRL7-Nov-02 6:20 
GeneralInteresting approach PinmemberMarc Clifton24-Oct-02 9:02 
GeneralRe: Interesting approach PinmemberGriffonRL24-Oct-02 13:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 24 Oct 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid