Search code examples
c#loggingenterprise-library

Padding Severity Level Field in Enterprise Library Logger


I am attempting to find a way of padding out fields within the enterprise logger library Text Formatter.

The current format of my log file entries is as follows:

02/01/2015 15:36:43.946|Information|Test Information Message
02/01/2015 15:36:43.946|Error|Test Error Message

However for ease of readability in a text based viewer like notepad, I would like them to be formatted as follows:

02/01/2015 15:36:43.946|Information|Test Information Message
02/01/2015 15:36:43.946|Error      |Test Error Message

Is this something that can be achieved in the configuration of the tokens or would a custom formatter be needed and if so are there any good examples that would give me a start point for what I am trying to achieve.

Also is there anyway to display a single value from the extended properties collection within a log entry?


Solution

  • There are a few ways to do what you want. One way is a custom formatter (as you mention). Another option is to create a custom LogEntry:

    [System.Xml.Serialization.XmlRoot("paddedLogEntry")]
    [Serializable]
    public class PaddedLogEntry : LogEntry
    {
        public string PaddedSeverity
        {
            get
            {
                return this.Severity.ToString().PadRight(11);
            }
        }
    }
    
    LogWriter logger = new LogWriterFactory().Create();
    PaddedLogEntry logEntry1 = new PaddedLogEntry()
    {
        Message = "Testing 123...",
        Severity = System.Diagnostics.TraceEventType.Information
    };
    logEntry1.Categories.Add("General");
    logger.Write(logEntry1);
    

    Using a template string: {timestamp}|{property(PaddedSeverity)}|{message}.

    Instead of creating a custom LogEntry you could also piggyback on the ExtendedProperties:

    LogEntry logEntry3 = new LogEntry()
    {
        Message = "Oops!",
        Severity = System.Diagnostics.TraceEventType.Error
    };
    logEntry3.Categories.Add("General");
    var extendedProperties = new Dictionary<string, object>();
    extendedProperties.Add("PaddedSeverity", logEntry3.Severity.ToString().PadRight(11));
    logEntry3.ExtendedProperties = extendedProperties;
    logger.Write(logEntry3);
    

    Using a template string: {timestamp}|{keyvalue(PaddedSeverity)}|{message}.

    Also is there anyway to display a single value from the extended properties collection within a log entry?

    The answer is yes. In the last template, I use that approach with the {keyvalue(PaddedSeverity)} token.