Click here to Skip to main content
11,565,382 members (43,158 online)
Click here to Skip to main content

Errors in XML Log with C#/.NET

, 23 Oct 2002 160.9K 940 39
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 -->

Introduction

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){
            Disposed=false;
            Writer=new XmlTextWriter(FilePath,Encoding.Unicode);

            // Write header
            Writer.Formatting=Formatting.Indented;
            Writer.WriteStartDocument();
            Writer.WriteStartElement("error");
            Writer.Flush();
            }

        // Destructor (equivalent to Finalize() without the need to call base.Finalize())
        ~ErrorLogWriter(){
            Dispose(false);
            }

        // Free resources immediately
        protected override void Dispose(bool Disposing){
            if(!Disposed){
                if(Disposing){
                    }
                // Close file
                Writer.Close();
                Writer=null;
                // Disposed
                Disposed=true;
                // Parent disposing
                base.Dispose(Disposing);
                }
            }

        // Close the file
        public override void Close(){
            // Write footer
            Writer.WriteEndElement();
            Writer.WriteEndDocument();
            Writer.Flush();
            // Free resources
            Dispose(true);
            GC.SuppressFinalize(this);
            }

        // Implement Encoding() method from TextWriter
        public override Encoding Encoding{
            get{
                return(Encoding.Unicode);
                }
            }

        // Implement WriteLine() method from TextWriter (remove MethodImpl attribute for single-threaded app)
        // Use stack trace and reflection to get the calling class and method
        [MethodImpl(MethodImplOptions.Synchronized)]
        public override void WriteLine(string Txt){
            Writer.WriteStartElement("event");
            Writer.WriteStartElement("time");
            Writer.WriteString(DateTime.Now.ToLongTimeString());
            Writer.WriteEndElement();
            Writer.WriteStartElement("class");
            Writer.WriteString(new StackTrace().GetFrame(2).GetMethod().ReflectedType.FullName);
            Writer.WriteEndElement();
            Writer.WriteStartElement("method");
            Writer.WriteString(new StackTrace().GetFrame(2).GetMethod().ToString());
            Writer.WriteEndElement();
            Writer.WriteStartElement("text");
            Writer.WriteString(Txt);
            Writer.WriteEndElement();
            Writer.WriteEndElement();
            Writer.Flush();
            }
        }
    }

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>
        [STAThread]
        static void Main(string[] args){
            // Here is the magic (file in .exe current directory)
            ErrorLogWriter Err=new ErrorLogWriter(Directory.GetCurrentDirectory()+@"\Error.xml");
            Console.SetError(Err);

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

            // Close error file
            Err.Close();

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

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

Conclusion

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 !!!

License

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
Generallog4net Pin
Jonathan de Halleux14-May-03 1:48
memberJonathan de Halleux14-May-03 1:48 
GeneralRe: log4net Pin
GriffonRL14-May-03 2:23
memberGriffonRL14-May-03 2:23 
GeneralSuggestion for improvement Pin
Anthony_Yio16-Jan-03 16:20
memberAnthony_Yio16-Jan-03 16:20 
GeneralRe: Suggestion for improvement Pin
Anthony_Yio16-Jan-03 16:26
memberAnthony_Yio16-Jan-03 16:26 
GeneralRe: Suggestion for improvement Pin
GriffonRL16-Jan-03 22:16
memberGriffonRL16-Jan-03 22:16 
GeneralLogging to XML Pin
Kiliman26-Dec-02 9:24
memberKiliman26-Dec-02 9:24 
GeneralRe: Logging to XML Pin
GriffonRL26-Dec-02 22:26
memberGriffonRL26-Dec-02 22:26 
GeneralRe: Logging to XML Pin
Heath Stewart21-Jan-03 4:42
memberHeath Stewart21-Jan-03 4:42 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 1:22
memberGriffonRL22-Jan-03 1:22 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 2:13
memberHeath Stewart22-Jan-03 2:13 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 2:19
memberHeath Stewart22-Jan-03 2:19 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 2:29
memberGriffonRL22-Jan-03 2:29 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 2:41
memberHeath Stewart22-Jan-03 2:41 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 3:39
memberGriffonRL22-Jan-03 3:39 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 3:51
memberHeath Stewart22-Jan-03 3:51 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 4:08
memberGriffonRL22-Jan-03 4:08 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 4:18
memberHeath Stewart22-Jan-03 4:18 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 3:25
memberGriffonRL22-Jan-03 3:25 
Hello,

Yes logging must be fast, but it also depends on the amount of informations you log. If you log not so often, the logging process will not be an issue. Yes this particular solution (very basic indeed) is not running on a separate thread and may raise some concerns, but multi-threading, just like XML is not always the best solution. Sometimes keeping the number of threads low helps helps saving some CPU cycles wasted by thread synchronisation and other mechanisms. When logging or whatsoever in a thread, it is the job of the programmer to avoid a long blocking operation.
Speaking about performance, it is everything in the business, but it depends of what kind of app you are developing.
Performance is a more bigger subject than just XML. Ok you can save CPU cycles with a efficient homemade logging system, but maybe you waste somewhere else because you believe you should use this specific utility class or library. And if we talk about performance, we could argue that C# gives worse results than C++, assembly code is faster than C++ and so on...
We have to be reasonable to find what the business is really looking for: a good balance between performance, reduced time to market and ease of maintenance/update.
I agree with you about the stupid idea of using XML instead of a very large database. It makes very much sense. It is one example of being reasonable.

Regards,


R. LOPES
Just programmer.
GeneralRe: Logging to XML Pin
justinj22-Feb-03 16:21
sussjustinj22-Feb-03 16:21 
GeneralRe: Logging to XML Pin
GriffonRL23-Feb-03 20:54
memberGriffonRL23-Feb-03 20:54 
GeneralRe: Logging to XML Pin
ltphu200117-May-04 14:27
memberltphu200117-May-04 14:27 
GeneralRe: Logging to XML Pin
reborn_zhang26-Nov-09 3:18
memberreborn_zhang26-Nov-09 3:18 
GeneralErrorLogger Pin
xptom9-Dec-02 10:10
memberxptom9-Dec-02 10:10 
GeneralRe: ErrorLogger Pin
GriffonRL9-Dec-02 21:59
memberGriffonRL9-Dec-02 21:59 
GeneralHere is an example output Pin
GriffonRL25-Oct-02 3:24
memberGriffonRL25-Oct-02 3:24 

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
Web04 | 2.8.150624.2 | Last Updated 24 Oct 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid