練習 3:建立與使用自訂 LogFormatter
建立自訂 LogFormatter 並在應用程式中使用。
開啟 EnoughPI.sln,預設路徑 C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Logging\exercises\ex03\begin,編譯。
Formatters\XmlFormatter.cs,加入命名空間:using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
XmlFormatter 類別加入代碼:[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();
}
}
}
日誌項目格式化為 XML,預期接收 prefix 與 namespace 兩個參數。
Build → Build Solution後續將在配置工具中註冊此自訂 Formatter 並套用至 TraceListener。