Click here to Skip to main content
13,358,244 members (57,456 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 2:48
memberJonathan de Halleux14-May-03 2:48 
GeneralRe: log4net Pin
GriffonRL14-May-03 3:23
memberGriffonRL14-May-03 3:23 
Hi Jonathan,

I know Log4j because I used to program in Java. And I know Log4Net. This is a great product, far more complicated and heavy than this little solution. I think it is really well suited for websites (something this log can't do) and professionnal projects where you can enjoy the SMTP and UDP features of Log4Net for example.
I use this little log solution for my little projects. In that case I don't need the Log4Net artillery.
For a very critical website or huge project I will may sign for Log4Net, but you should also look at the Tracelistener capabilities built-in the .NET framework. Something we could maybe argue against Log4Net is that it is originally a Java port and doesn't rely on all the available features of .NET. Creating another full featured logging system very .NET oriented will be interresting, even if Log4Net is already up for the job. But if you have some time to spare...
Also take a look on the messages at the bottom of this page. The last one, I believe, provides 2 links to other solutions.


Just programmer.
GeneralSuggestion for improvement Pin
Anthony_Yio16-Jan-03 17:20
memberAnthony_Yio16-Jan-03 17:20 
GeneralRe: Suggestion for improvement Pin
Anthony_Yio16-Jan-03 17:26
memberAnthony_Yio16-Jan-03 17:26 
GeneralRe: Suggestion for improvement Pin
GriffonRL16-Jan-03 23:16
memberGriffonRL16-Jan-03 23:16 
GeneralLogging to XML Pin
Kiliman26-Dec-02 10:24
memberKiliman26-Dec-02 10:24 
GeneralRe: Logging to XML Pin
GriffonRL26-Dec-02 23:26
memberGriffonRL26-Dec-02 23:26 
GeneralRe: Logging to XML Pin
Heath Stewart21-Jan-03 5:42
memberHeath Stewart21-Jan-03 5:42 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 2:22
memberGriffonRL22-Jan-03 2:22 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 3:13
memberHeath Stewart22-Jan-03 3:13 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 3:19
memberHeath Stewart22-Jan-03 3:19 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 3:29
memberGriffonRL22-Jan-03 3:29 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 3:41
memberHeath Stewart22-Jan-03 3:41 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 4:39
memberGriffonRL22-Jan-03 4:39 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 4:51
memberHeath Stewart22-Jan-03 4:51 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 5:08
memberGriffonRL22-Jan-03 5:08 
GeneralRe: Logging to XML Pin
Heath Stewart22-Jan-03 5:18
memberHeath Stewart22-Jan-03 5:18 
GeneralRe: Logging to XML Pin
GriffonRL22-Jan-03 4:25
memberGriffonRL22-Jan-03 4:25 
GeneralRe: Logging to XML Pin
justinj22-Feb-03 17:21
sussjustinj22-Feb-03 17:21 
GeneralRe: Logging to XML Pin
GriffonRL23-Feb-03 21:54
memberGriffonRL23-Feb-03 21:54 
GeneralRe: Logging to XML Pin
ltphu200117-May-04 15:27
memberltphu200117-May-04 15:27 
GeneralRe: Logging to XML Pin
reborn_zhang26-Nov-09 4:18
memberreborn_zhang26-Nov-09 4:18 
GeneralErrorLogger Pin
xptom9-Dec-02 11:10
memberxptom9-Dec-02 11:10 
GeneralRe: ErrorLogger Pin
GriffonRL9-Dec-02 22:59
memberGriffonRL9-Dec-02 22:59 
GeneralHere is an example output Pin
GriffonRL25-Oct-02 4:24
memberGriffonRL25-Oct-02 4: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
Web04 | 2.8.180111.1 | Last Updated 24 Oct 2002
Article Copyright 2002 by GriffonRL
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid