【问题标题】:Enterprise Library 5.0 - Adding custom tokens to a TextFormatterEnterprise Library 5.0 - 将自定义标记添加到 TextFormatter
【发布时间】:2011-08-10 08:18:26
【问题描述】:

我创建了一个自定义异常,其中包含与我们的应用程序相关的数据。我想确保在引发异常并记录到事件日志时记录这些数据。

我已尝试创建一个正在调用的自定义 TextFormatter,但不确定如何访问当前异常,因此我可以将自定义信息添加到日志条目中。

有一些我不明白的地方,如果在将自定义令牌(和数据)添加到 Enterprise Library 5.0 TextFormatters 方面提供任何帮助,我将不胜感激。

谢谢, ...马克

【问题讨论】:

    标签: logging exception-handling enterprise-library


    【解决方案1】:

    您可以扩展TextFormatter。我认为问题在于TextFormatter 格式化LogEntry

    public override string Format(
        LogEntry log
    )
    

    因此,您需要将自定义数据放入 LogEntry。 (我认为这就是您的问题所在。)

    另一种(我认为更简单)的方法是使用ExtendedPropertiesLogEntry。如果您使用异常处理块 (EHAB) 记录异常,则可以将所有自定义信息添加到 IDictionary Data 属性。在运行时,数据字典的内容被添加到ExtendedProperties。然后可以使用格式化程序定义中的标记来记录特定属性。

    例如

    public class MyException : Exception
    {
        private string myCustomProperty;
    
        public string MyCustomProperty
        {
             get
             {
                 return myCustomProperty;
             }
             set
             {
                 myCustomProperty = value;
                 Data["MyCustomProperty"] = value;
             }
        }
    }
    

    然后您可以使用带有日志记录策略的 EHAB 处理异常:

    ExceptionPolicy.HandleException(ex, "Logging Exception Handler");
    

    在您的模板中添加如下内容:

    MyCustomProperty: {keyvalue(MyCustomProperty)}

    这将记录您的自定义属性。

    如果您没有使用 EHAB,那么您可以在您的异常类中设置 Data 值,然后创建小型帮助程序类以将您的自定义属性添加到 ExtendedProperties

    public void LogException(Exception ex)
    {
        LogEntry logEntry = new LogEntry();
        //...
        logEntry.ExtendedProperties.Add("MyCustomProperty", ex.MyCustomProperty);
    
        Logger.Write(logEntry);
    }
    

    如果自定义异常属性的日志记录对您来说是一个普遍问题,那么您可以将所有自定义属性添加到 Data 字典中,然后在辅助方法中将所有 Data 键/值对复制到 ExtendedProperties。

    【讨论】:

      【解决方案2】:

      Extensibility Hands-On Labs 的 Lab2 提供有关构建自定义跟踪侦听器和文本格式化程序的分步指导。

      【讨论】:

        猜你喜欢
        • 2012-01-21
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 2011-08-27
        • 1970-01-01
        相关资源
        最近更新 更多