練習3:創建並使用自定義LogFormatter
在本練習中將創建一個自定義的LogFormatter,並在應用程序中使用它。
第一步
打開EnoughPI.sln項目,默認的安裝路徑應該為C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Logging\exercises\ex03\begin,並編譯。
第二步 創建自定義LogFormatter
1.在解決方案管理器中選擇Formatters\XmlFormatter.cs文件,選擇View | Code菜單命令,添加如下命名空間。
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
2.添加如下代碼到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。
3.選擇Build | Build Solution編譯整個解決方案。