Logging Formatter

Topics: Logging Application Block
Aug 11, 2009 at 4:48 PM

How can I modify the formatterTemplate of the text formatter? I want for a specific scenario just to log the date and the message and other time I want to log all the information? How is that possible?

Aug 11, 2009 at 7:56 PM

Using the configuration UI:

1) create two Text Formatters.  You can name them, for example, "Terse Text Formatter" and "Verbose Text Formatter" respectively.  Edit the Template for "Terse Text Formater" to read merely "Timestamp: {timestamp} Message: {message}"

2) create a Trace Listener for each of the two Formatters.

3) create a Logging Category for each of the two Trace Listeners.

4) in your code, dynamically assign the Category based upon your specific scenario.

hope this helps,


Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}


Aug 12, 2009 at 4:59 AM


I agree with that. The suggestion of kstout is a possible solution. That works perfectly with the FormattedEventLog TraceListener. But I think there would be a problem if you are logging on a file based trace listener (ex: FlatFile) and you have a single file destination(ex: you have 2 flatFile trace listener which has the same filename). The effect would be you will have 2 file created, one is the original filename and the other is the one pre-fixed with guid. If you will be using a FormattedEventLog TraceListener then you can follow the suggestion above. But if you would be logging to a file base trace listener, One thing you can do is to create a single trace listener and create the required formatters. Then in your code, you would need to edit the associated formatter on the trace listener when needed.

Here is a sample snippet which assigns a formatter to a trace listener:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "YourConfig.config";
Configuration entLibConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
//get the trace listener
FlatFileTraceListenerData flatFileData = loggingSettings.TraceListeners.Get("FlatFile TraceListener") as FlatFileTraceListenerData;
//get the formatter
TextFormatterData textFormatterData = loggingSettings.Formatters.Get("Text Formatter") as TextFormatterData;
//assign the formatter to the trace listener
if (flatFileData != null)
    if (textFormatterData != null)
        flatFileData.Formatter = textFormatterData.Name;
Valiant Dudan
Global Technology and Solutions
Avanade, Inc.