Search code examples
c#loggingetw

How to register an EventSource etw provider C# and capture the output to a log file.?


I created a "Logger" class that derives from the base class EventSource (event provider). I used this to instrument my application. Now, to view the trace messages logged by my application I use the perfview GUI tool - I first register my event provider "*Logger" and then start the collection process through this tool. Once the collection is done I can view my logged events.This works fine, but I need to automate the process.

When trying to automate this process I am faced with two issues:

  1. How do I register my event provider (preferably using c# libraries only or Microsoft provided CLI tools[don't want to use any third party tools or libraries to do this.])
  2. How do I collect the logged events into an etl file using tools like Logman (or any other command line tools).

I have provided my application source code below (The code very basic and straight forward.):

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Diagnostics.Tracing;
    using System.Threading;

    namespace EventLogging
    {
    class Program
    {
    static void Main(string[] args)
    {
        Logger log = Logger.GetLogger();
        for (int i = 0; i < 100000; i++)
        {
            log.WriteError("Logging some serious error",i);
            log.WriteWarning("Logging warning",i);
        }

    }
    }

    /// <summary>
    /// Logger writes to instance.
    /// 
    /// </summary>
    class Logger : EventSource
    {   
    /// <summary>
    /// 
    /// </summary>
    static private Logger _log;

    /// <summary>
    /// only one instance of Logger can be created.
    /// </summary>

    public static Logger GetLogger(){
        if (_log == null)
            return (_log = new Logger());
        else
            return _log;
    }
    private Logger()
        : base()
    {

    }

    [Event(101,Message="Application Failure Message: {0}",Level=EventLevel.Error)]
       public void WriteError(String message1,int value){

        WriteEvent(101, message1,value);

    }
    [Event(102,Message="Application Warning Message: {0}",Level=EventLevel.Warning)]
    public void WriteWarning(String message,int value)
    {
        WriteEvent(102, message,value);
    }




    }


    }

Solution

  • Microsoft TraceEvent Library enables you to capture and process ETW traces. It understands EventSource, so there is no reason to register anything. See here, here and here.