Click here to Skip to main content
12,952,398 members (44,525 online)
Click here to Skip to main content
Add your own
alternative version


40 bookmarked
Posted 23 Oct 2002

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

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 
Whoa whoa whoa, hold on there. I've been researching and developing with XML since it was still a wet-dream to most people. I truly believe in XML and have done a lot of work with it. But a good advocate knows when his or her subject isn't the best solution. XML is great for may things and does solve many problems, but it doesn't solve all of them. Platform-agnostic solutions are difficult at best without a standard capable of expansion like XML. Many applications like Office (currently, when you save as HTML it's actually saved as XHTML, but future versions will apparently use XML for native formats if I gather correctly), StarOffice, and many others use XML and would allow for any application to read-in their files on any platform. Only a couple years ago this was a very difficult thing to accomplish and always involved having to develop such documents or applications with little help from frameworks.

However, it still doesn't work for everything. Take, for example, the current solution I architected for work that relies on remoting on a system that must be extremely scalable since it's an Internet-based Windows Forms application with a remote DB. With remoting (even exposed as a Web Service for firewall'd clients) we can either use a SOAP formatter or binary formatter. With SOAP, a DOM must be created in memory to serialize data correctly, then transfered across the wire in a Unicode format (so 2 bytes per character, already twice the size to transfer), then reconstructed so the server can deserialize using the DOM. A lot of memory, CPU time, and throughput are wasted. If we use a binary formatter, the size is consistent and serialization is much faster since a DOM is not used on either side. There are many other examples where XML may not be the right choice. That's the only point I'm trying to make here.

If you are just writing XML as text, so be it. I was just warning about the implications of using the DOM because - as I said before - logging must be faster and having a potentially large tree in memory (most of which is probably in the pagefile) that must be parsed just to add a new "record".

"Well, I wouldn't say I've been missing it, Bob." - Peter Gibbons
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 
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    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170525.1 | Last Updated 24 Oct 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid