Home > View Post

Using tokens in Ukadc.Diagnostics to control output

This is part 2 in a series introducing the Ukadc.Diagnostics project which is currently hosted on codeplex at www.codeplex.com/UkadcDiagnostics.

In the previous post we took a look at adding some basic logging to a very simple console application using System.Diagnostics. We also looked at how we could modify the output using the traceOutputOptions attribute. Today we'll look at using a similar listener provided with Ukadc.Diagnostics and controlling the output using tokens.

And the best part is that to use Ukadc.Diagnostics we don't need to make any changes to our code!

All we have to do is drop the Ukadc.Diagnostics assembly (Ukadc.Diagnostics.dll) next to the EXE and make a couple of changes to the configuration file:

<configuration>
    <system.diagnostics>
        <sources>
            <source name="primes" switchValue="All">
                <listeners>
                    <add
                        name="console"
                        type="Ukadc.Diagnostics.Listeners.ConsoleTraceListener, Ukadc.Diagnostics"
                        initializeData="{EventType}: {Message}
    ProcessId={ProcessId},
    ThreadId={ThreadId},
    Timestamp={Timestamp}"
/>
                </listeners>
            </source>
        </sources>
    </system.diagnostics>
</configuration>

The main difference is the change of type from System.Diagnostics.ConsoleTraceListener to Ukadc.Diagnostics.Listeners.ConsoleTraceListner (note how we have to specify the name of the assembly also). We then use the initializeData attribute to specify the format of the output and create placeholders for the data using tokens. Here's the result:

Console window with logging turned on

Notice how we have simulated the output of the last example in the previous post but we don't have to do this. We can format it however we like, including getting everything on one line and using any of the available tokens including:
  • {Message}
  • {Id}
  • {ThreadId}
  • {ProcessId}
  • {Callstack}
  • {DateTime}
  • {EventType}
  • {Source}
  • {ActivityId}
  • {RelatedActivityId}
  • {MachineName}
  • {Timestamp}


<add
    name="console"
    type="Ukadc.Diagnostics.Listeners.ConsoleTraceListener, Ukadc.Diagnostics"
    initializeData="Hello! Found a prime: {{EventType}} {ProcessId}, {DateTime}" />

Custom formatting

I do plan to add more tokens very shortly and thankfully this is very easy to do. What's even better is that you don't have to wait - you can add your own through configuration! We'll look at how to do this in the next post.

 
Josh Post By Josh Twist
12:17 AM
29 Apr 2008

» Next Post: Creating your own tokens
« Previous Post: From zero to logging with System.Diagnostics in 15 minutes

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.