Exercise 3: Create and use a custom Logformatter
In this exercise you will create a custom logformatter and use it in your application.
First step
Open the EnoughPI.sln project, the default installation path should be C:\Program Files\Microsoft Enterprise Library January Ex03\begin, and compiled.
The second step is to create a custom Logformatter
1. Select the Formatters\xmlformatter.cs file in Solution Manager, select View | Code menu command, add the following namespaces.
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
Using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
2. Add the following code to the Xmlformatter class.
[ConfigurationElementType (typeof (Customformatterdata))]
public class Xmlformatter:logformatter
{
Private NameValueCollection Attributes = null;
Public xmlformatter (NameValueCollection attributes)
{
This. Attributes = Attributes;
}
public override string Format (LogEntry log)
{
String prefix = this. attributes["prefix"];
string ns = this. Attributes["namespace"];
using (StringWriter s = new StringWriter ())
{
XmlTextWriter w = new XmlTextWriter (s);
w.formatting = formatting.indented;
W.indentation = 2;
W.writestartdocument (TRUE);
W.writestartelement (prefix, "LogEntry", NS);
W.writeattributestring ("Priority", NS,
Log. Priority.tostring (CultureInfo.InvariantCulture));
W.writeelementstring ("Timestamp", NS, log. timestampstring);
W.writeelementstring ("message", NS, log.) message);
W.writeelementstring ("EventId", NS,
Log. Eventid.tostring (CultureInfo.InvariantCulture));
W.writeelementstring ("Severity", NS, log. Severity.tostring ());
W.writeelementstring ("Title", NS, log. Title);
W.writeelementstring ("Machine", NS, log. MachineName);
W.writeelementstring ("AppDomain", NS, log. Appdomainname);
W.writeelementstring ("ProcessID", NS, log. ProcessID);
W.writeelementstring ("ProcessName", NS, log. ProcessName);
W.writeelementstring ("Win32threadid", NS, log. Win32threadid);
W.writeelementstring ("ThreadName", NS, log. Managedthreadname);
W.writeendelement ();
W.writeenddocument ();
return s.tostring ();
}
}
}
The log entry is formatted as XML, and it expects to receive two parameters prefix and namespace.
3. Select Build | Build solution compiles the entire solution.