c# - 带有企业应用程序 block 的自定义跟踪监听器

标签 c# logging enterprise-library

我目前从事的项目使用 Enterprise Libraries V3.1 框架进行日志记录。

我需要获取生成的日志文件并在特定点将其存档。内置的跟踪监听器似乎使文件在日志记录事件之间保持打开状态。我已经设置了一个自定义跟踪监听器,它将附加到文件并关闭它,以便文件始终可以移动。

它看起来像这样(为清楚起见减去错误处理):

[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class AlwaysClosedTextFileTraceListener : CustomTraceListener
{
    private string logFilePath;

    public AlwaysClosedTextFileTraceListener ()
    {
        logFilePath = @"hardcodedpath\log.txt";
    }

    public override void Write(string message)
    {
        using (StreamWriter logFile = File.AppendText(logFilePath))
        {
            logFile.Write(message);
            logFile.Flush();
            logFile.Close();
        }
    }

    public override void WriteLine(string message)
    {
        using (StreamWriter logFile = File.AppendText(logFilePath))
        {
            logFile.WriteLine(message);
            logFile.Flush();
        }
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        if (data is LogEntry && this.Formatter != null)
        {
            WriteLine(this.Formatter.Format(data as LogEntry));
        }
        else
        {
            WriteLine(data.ToString());
        }
    }
}

这很好用,但我更愿意以某种方式将路径作为参数传递,而不是对其进行硬编码。

为了好玩,我尝试将它添加到构造函数中,看看会发生什么:

    public LogFolderTraceListener(string logFilePath)
    {
        this.logFilePath = logFilePath;
    }

当我这样做时,我收到一条错误消息,提示我做错了什么:

System.InvalidOperationException : The type 'AlwaysClosedTextFileTraceListener' specified for custom trace listener named 'MyLogFile' does not a default constructor, which is required when no InitData is specified in the configuration.

从现在开始,我的调查非常明确,与死胡同相反,无限概率问题。

我翻阅了内置 RollingTraceListener 的源代码发现了这一点

  • 有一个类 RollingFlatFileTraceListenerData : TraceListenerData 似乎包含传递给构造函数的所有设置
  • RollingFlatFileTraceListenerData 的文件底部驻留的是 RollingTraceListenerAssembler : TraceListenerAsssembler 类,它似乎是一个工厂
  • 还有另一个类 SystemDiagnosticsTraceListenerNode : TraceListenerNode,它似乎使 Data 类可呈现给配置应用程序

我的问题是:如何创建具有 path 可配置参数的 CustomTraceListener

最佳答案

CustomTraceListener 派生自 TraceListener,它有一个名为 Attributes 的 StringDictionary。

这将包含您的 TraceListener 配置行中的所有属性,并且可以通过名称获取,例如。

string logFileName= Attributes["fileName"]

关于c# - 带有企业应用程序 block 的自定义跟踪监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/530385/

相关文章:

java - 通过 SSH 在远程计算机上运行 jar 时未创建日志

c# - 为什么在调用 ExceptionPolicy.HandleException 时会出现 System.InvalidOperationException?

c# - 记录应用程序 block 不记录到文件

.net - 使用 Ent-Lib 拨号跟踪的意外后果,没有错误记录

c# - EqualityComparer<T>.Default 误解?

c# - ASP.NET Web Api 获取 token 跨域时出现问题

Tomcat JNDI 领域日志记录

logging - 是否有一种工具可以轻松地以聚合方式从 AWS Elastic Beanstalk 搜索 S3 中每小时轮换的日志?

c# - 应用程序在 Windows 10 中处于后台时的位置跟踪?

c# - 是否有必要在交易中包装 nHibernate future ?