0
public sealed class Logger
{
    private static TraceSource myTraceSource;

    private Logger()
    {
    }

    public static TraceSource Create()
    {
        if (myTraceSource == null)
            return myTraceSource = new TraceSource("myTraceSource");
        else
            return myTraceSource;
    }

    public static void WriteInfo(string message)
    {
        myTraceSource.TraceEvent(TraceEventType.Information, 0, message);
        myTraceSource.Flush();
    }

    public static void WriteError(Exception ex)
    {
        myTraceSource.TraceEvent(TraceEventType.Error, 1, ex.Message);
        myTraceSource.Flush();            
    }

    public static void WriteError(string message)
    {
        myTraceSource.TraceEvent(TraceEventType.Error, 1, message);
        myTraceSource.Flush();
    }

    public static void WriteWarning(string message)
    {
        myTraceSource.TraceEvent(TraceEventType.Warning, 2, message);
        myTraceSource.Flush();
    }

    public static void AddListener(TraceListener listener)
    {
        myTraceSource.Listeners.Add(listener);
    }

    public static void Close()
    {
        if (myTraceSource != null)
        {
            myTraceSource.Flush();
            myTraceSource.Close();
        }
    }       
}

Below is the code to initialize the trace source and add listener

Logger.Create();
TextWriterTraceListener myTextListener = new TextWriterTraceListener(LogCompletePath);
Logger.AddListener(myTextListener);
Logger.WriteError("error");

Note I have not put the SytemDiagnostic tag in appconfig as I want to do it in code.

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
Rishikesh
  • 486
  • 6
  • 15

1 Answers1

4

Got the answer in another forum. I forgot to mention Source Level and by default it is set to off

 return myTraceSource = new TraceSource("myTraceSource", SourceLevels.All); 
Rishikesh
  • 486
  • 6
  • 15
  • 2
    If anyone is trying to do this with the Mono framework, there appears to be a bug in the TraceSource constructor, so that the SourceLevels you provide may not be used. As a workaround, set myTraceSource.Switch.Level = SourceLevels.All after construction. (I'm using the modified version of Mono 2.6 that ships with the Unity 4.1 game engine.) – yoyo Aug 15 '13 at 21:01
  • Looks like I'm not the first to find the TraceSource constructor bug: http://mono.1490590.n4.nabble.com/Bug-in-TraceSource-td3201651.html – yoyo Aug 15 '13 at 21:50