寻求更清洁的NLog条件布局

时间:2017-07-22 01:47:39

标签: nlog

我希望区分我的日志条目,具体取决于它们是否包含异常。我正在写Windows事件日志,所以我选择将我的'列'名称放在左边,如下所示:

Method:     PowerDown.Tests.MainTest.TestLogging()
Message:    This is an NLog test entry.

当事件不包含异常时,将呈现此内容。但是,当事件包含异常时,我会改变我的布局来生成它:

Method:     PowerDown.Tests.MainTest.TestExceptionLogging()
Exception:  System.Exception: This is an NLog test exception.
   at PowerDown.Tests.MainTest.TestExceptionLogging() in D:\Dev\Customers\OIT\Active\PowerDown\Application\PowerDown.Tests\MainTest.vb:line 17

我已经完成了所有这些工作,但代码感觉相当笨拙且过于复杂。有没有办法在没有自定义布局渲染器的情况下本地完成此操作?

(注意:我希望保留基于运行时的NLog配置,如下所示。配置文件不适合当前环境。)

代码:

Public Shared Function GetLogger(Name As String) As Logger
  Dim oBuilder As StringBuilder
  Dim oConfig As LoggingConfiguration
  Dim oTarget As EventLogTarget
  Dim sLayout As String
  Dim oRule As LoggingRule

  LayoutRenderer.Register("event-log", Function(LogEvent)
                                         If LogEvent.Exception Is Nothing Then
                                           sLayout = $"Message:{vbTab}{LogEvent.Message}{vbCrLf}"
                                         Else
                                           With LogEvent.Exception
                                             sLayout = $"Exception:{vbTab}{ .GetType.FullName}: { .Message}{vbCrLf}{ .StackTrace}{vbCrLf}"
                                           End With
                                         End If

                                         Return sLayout
                                       End Function)

  oBuilder = New StringBuilder
  oBuilder.Append($"Method:{vbTab}{vbTab}${{callsite}}()${{newline}}")
  oBuilder.Append("${event-log}")

  oTarget = New EventLogTarget("Event") With {
    .Layout = oBuilder.ToString,
    .Source = Name
  }

  oRule = New LoggingRule("*", LogLevel.Debug, oTarget)

  oConfig = New LoggingConfiguration
  oConfig.LoggingRules.Add(oRule)
  oConfig.AddTarget(oTarget)

  LogManager.Configuration = oConfig

  Return LogManager.GetLogger(Name)
End Function

0 个答案:

没有答案