企业库日志记录 - 如何在运行时获取配置的日志记录级别?

Ste*_*enH 5 c# logging enterprise-library

我们使用 Enterprise Library 4.1 进行日志记录(和异常处理/加密)。

有谁知道在运行时确定配置的日志记录级别的好方法吗?我编写了一个 LogUtility 类来进行日志记录调用,并按照以下示例调用它:

LogUtility.LogVerbose(
    string.Format("Processing event {0}", currentEvent.EventIDImported), 
    MethodBase.GetCurrentMethod().Name, 
    this.GetType().Name
);
Run Code Online (Sandbox Code Playgroud)

我知道它实际上不会被记录到文件中,除非将日志记录级别设置为适当的级别,在我的情况下是在 app.config 中。但我真的不希望方法参数,即方法和类型名称,以及在某些情况下记录的实际字符串,除非绝对必要,否则会被评估。

这似乎是一个合理的担忧吗?我们的应用程序可以有数千万次迭代和记录点。如果可能,我想根据配置的日志级别设置一个标志,并在调用上述方法之前进行检查。

编辑 - 我想就上面的例子而言,我可以在每次调用时硬编码方法和类型名称。但我还是想知道是否有一种确定水平的方法。

Ran*_*ica 2

除非绝对必要,否则我真的不希望对方法参数(即方法和类型名称,以及在某些情况下记录的实际字符串)进行评估。

基于以上我认为你应该看看ShouldLog的方法LogWriter。它将让您确定是否LogEntry将根据当前配置进行记录,并且您可以(希望)避免创建不需要的对象。

借用 Enterprise Library 4.1演练:构建日志消息之前检查过滤器状态的代码:

LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");

if (Logger.ShouldLog(logEntry))
{
  // Perform operations (possibly expensive) to gather additional information 
  // for the event to be logged. 
}
else
{
  // Event will not be logged. Your application can avoid the performance
  // penalty of collecting information for an event that will not be
  // logged.
}
Run Code Online (Sandbox Code Playgroud)

由于您使用自己的LogUtility类,您可能希望在LogUtility调用ShouldLogVerbose或创建一个静态属性IsVerboseEnabled,并在该属性内部使用“正确”构造LogEntry(针对您的应用程序)来确定是否将记录消息。例如

if (LogUtility.IsVerboseEnabled)
{
    LogUtility.LogVerbose(
        string.Format("Processing event {0}", currentEvent.EventIDImported), 
        MethodBase.GetCurrentMethod().Name, 
        this.GetType().Name
    );
}
Run Code Online (Sandbox Code Playgroud)