首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

Enterprise Library 2.0 Hands On Lab 翻譯(6):日誌應用程式區塊(三)

     編輯:關於ASP.NET

練習 3:建立與使用自訂 LogFormatter

建立自訂 LogFormatter 並在應用程式中使用。

步驟 1:開啟專案

開啟 EnoughPI.sln,預設路徑 C:\Program Files\Microsoft Enterprise Library January 2006\labs\cs\Logging\exercises\ex03\begin,編譯。

步驟 2:建立自訂 LogFormatter

  1. 開啟 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;
  1. 在 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 兩個參數。

  1. 編譯方案:Build → Build Solution

後續將在配置工具中註冊此自訂 Formatter 並套用至 TraceListener。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved