Logging: How to use XML formatter while logging

Topics: Exception Handling Application Block, Logging Application Block, Policy Injection Application Block
Mar 5, 2012 at 1:23 PM

Hi,

We are using Unity 2.0 along with Exception handling and Logging.  In the database, the formatted message column logged-in as in textformat. how to use XML formatter to log as in xml format ?

 

 

Thanks

Hari

Mar 6, 2012 at 6:33 AM

I'm assuming that you wish to insert XML into the FormattedMessageColumn.

Enterprise Library does contain an XML Formatter called XmlLogFormatter.  Unfortunately, it doesn't look like this is directly available for use via configuration because it is not attributed with the ConfigurationElementType attribute.  Luckily it's easy to create a new class that adds this:

    [ConfigurationElementType(typeof(CustomFormatterData))]
    public class MyXmlFormatter : XmlLogFormatter
    {
        public MyXmlFormatter(NameValueCollection nvc)
        {
        }
    }

Then this class can be used in the configuration as a formatter:

    <formatters>
        <add type="LoggingDatabase.MyXmlFormatter, LoggingDatabase" name="XML Formatter" />
    </formatters>

If that format doesn't suffice then another way to generate XML would be extend LogEntry and add an XML property that creates whatever XML format you are looking for.  Then you could use a TextFormatter where the template references that new property:

    public class MyLogEntry : LogEntry
    {
        public string XmlText
        {
            get
            {
                // Bad way to create XML -- just for demonstration
                return "<XML>" + this.Message + "<XML>";
            }
        }
    }

    <formatters>
        <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            template="{property(XmlText)}"
            name="XML Text Formatter" />
    </formatters>

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com