首页 / 网页编程 / ASP.NET / Enterprise Library 2.0 Hands On Lab 翻译(6):日志应用程序块(三)
Enterprise Library 2.0 Hands On Lab 翻译(6):日志应用程序块(三)2010-03-02 cnblogs TerryLee练习3:创建并使用自定义LogFormatter在本练习中将创建一个自定义的LogFormatter,并在应用程序中使用它。第一步打开EnoughPI.sln项目,默认的安装路径应该为C:Program FilesMicrosoft Enterprise Library January 2006labscsLoggingexercisesex03egin,并编译。第二步 创建自定义LogFormatter1.在解决方案管理器中选择FormattersXmlFormatter.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编译整个解决方案。