问题
I'm using the NLog.EventLog
target, and using the API I wish to log an event in vertical-field format.
It might look something like this:
Method: ServiceBase.Manager.StartService()
Message: The service started successfully.
Result: The service is listening for requests.
Is this possible?
回答1:
Sure, something like this:
<target name="file" xsi:type="File"
layout="Method: ${callsite} ${newline}Message: ${message} ${newline}Result: ${event-properties:result}"
fileName="${basedir}/${level}.log" />
Logging call, using NLog.Fluent namespace:
logger.Info().Message("The service started successfully.")
.Property("result", The service is listening for requests.")
.Write();
回答2:
Based on Julian's answer, I've come up with this:
--Configuration Method--
Protected Sub ConfigureLogging(ServiceName As String)
Dim oBuilder As StringBuilder
Dim oConfig As LoggingConfiguration
Dim oTarget As EventLogTarget
Dim oRule As LoggingRule
oBuilder = New StringBuilder
oBuilder.Append($"Method:{vbTab}{vbTab}{Layouts.CallSite}(){Layouts.NewLine}")
oBuilder.Append($"Level:{vbTab}{vbTab}{Layouts.Level}{Layouts.NewLine}")
oBuilder.Append($"Message:{vbTab}{Layouts.Message}{Layouts.NewLine}")
oTarget = New EventLogTarget("EventLog")
oTarget.Layout = oBuilder.ToString
oTarget.Source = ServiceName
oRule = New LoggingRule("*", LogLevel.Debug, oTarget)
oConfig = New LoggingConfiguration
oConfig.AddTarget(oTarget)
oConfig.LoggingRules.Add(oRule)
LogManager.Configuration = oConfig
Me.Logger = LogManager.GetLogger(ServiceName)
End Sub
--Helper Class--
Public Class Layouts
Public Sub New(Layouts As List(Of String))
Me.Layouts = Layouts
End Sub
Shared Sub New()
_CallSite = "${callsite}"
_Message = "${message}"
_NewLine = "${newline}"
End Sub
Public Overrides Function ToString() As String
Return Join(Me.Layouts.ToArray, "|")
End Function
Private Layouts As List(Of String)
''' <summary>
''' The call site (class name, method name and source information).
''' </summary>
Public Shared ReadOnly Property CallSite As String
''' <summary>
''' The formatted log message.
''' </summary>
Public Shared ReadOnly Property Message As String
''' <summary>
''' A newline literal.
''' </summary>
Public Shared ReadOnly Property NewLine As String
End Class
...which produces this:
Method: ServiceBase.Manager.StartService()
Level: Info
Message: Service started
It's the newline
layout that does the trick.
来源:https://stackoverflow.com/questions/43485413/how-to-log-using-vertical-fields-instead-of-horizontal-columns