-
Notifications
You must be signed in to change notification settings - Fork 20
Using EntLib6 ETW Listeners
*NOTE: this is based on a preview release and may not be the same as the final release *
One of the reasons that developers haven't adopted ETW yet is that they already have logging solutions. Usually they are home-grown flat-file or database logs, or are based on a library such as nLog or Log4Net. If you have one of these solutions, you can start using ETW now as your EventSources, but log the data to your existing back-end store.
The Microsoft Patterns and Practices Team is releasing a set of ETW listeners to handle all your logging target needs. The Semantic Logging Application Block is available on NuGet. It can handle logging to:
- ConsoleEventListener - logging to the console for development
- FlatFileEventListener - logging to a set of flat files as XML, JSON or Text
- RollingFlatFileEventListener - logging to a set of flat files that automatically rotates to a new file
- DatabaseEventListener - logging to a .NET database
- SqlDatabaseEventListener - logging to a SQL Server database
- AzureTableEventListener - logging to SQL Azure in the cloud
Let's take a look at a few of the listeners. The simplest is the ConsoleEventListener:
// create a logger
var log = EventSourceImplementer.GetEventSourceAs<ICalculatorEventSource>();
// create a console listener
ConsoleEventListener listener = new ConsoleEventListener();
// enable listening
listener.EnableEvents((EventSource)log, EventLevel.LogAlways, (EventKeywords)(-1));
log.Clear();
log.Add(1, 2);
This generates the following output:
SourceId : 5534a855-95dc-5099-33e3-5b8e79fed6fa
EventId : 1
Keywords : 1
Level : Informational
Message : Clear
Opcode : Info
Task : 65533
Version : 0
Payload :
EventName : ClearInfo
Timestamp : 2013-03-04T18:31:38.7621609Z
SourceId : 5534a855-95dc-5099-33e3-5b8e79fed6fa
EventId : 2
Keywords : 2
Level : Informational
Message : Add 1 2
Opcode : Info
Task : 65532
Version : 0
Payload : [x : 1] [y : 2]
EventName : AddInfo
Timestamp : 2013-03-04T18:31:38.7701619Z
As you can see, the listener found the events from our source and logged them to the console.
You can log them to a file just as easily:
// create a file listener
var listener = new FlatFileEventListener(@"c:\temp\calc.log");
The file listeners even let you control the format of the output, with built-in support for JSON or XML serialization:
var listener = new FlatFileEventListener(@"c:\temp\calc.log", new JsonEventTextFormatter());
The output is now:
{
"SourceId":"5534a855-95dc-5099-33e3-5b8e79fed6fa",
"EventId":2,
"Keywords":"2",
"Level":"Informational",
"Message":"Add 1 2",
"Opcode":"Info",
"Task":65532,
"Version":0,
"Payload":{"x":1,"y":2},
"EventName":"AddInfo",
"Timestamp":"2013-03-04T18:36:03.1511259Z"
},
Try it out. It supports almost any kind of output you might need.