Skip to content

NLog Console and AddConsole

Rolf Kristensen edited this page Apr 15, 2020 · 6 revisions

NLog Console vs AddConsole

The Microsoft AddConsole is asynchronous by default, but the console is still very slow. The asynchronous NLog Console Target is much faster and can produce the same output (The magic keyword is <targets async="true">):

<nlog  throwConfigExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <variable name="MicrosoftLevel" value="${level:lowercase=true:truncate=4:when=level==LogLevel.Info or level==LogLevel.Warn}${when:when=level==LogLevel.Error:inner=fail}${when:when=level==LogLevel.Fatal:inner=crit}${when:when=level==LogLevel.Debug:inner=dbug}" />
  <variable name="MicrosoftLayout" value="${MicrosoftLevel}: ${logger}[${event-properties:EventId_Id:whenEmpty=0}]${newline}      ${message}${onexception:inner=${newline}${exception:format=tostring}}" />

  <targets async="true">
    <target name="console" xsi:type="Console" layout="${MicrosoftLayout}" writeBuffer="true" />

    <target name="colorconsole" xsi:type="ColoredConsole" layout="${MicrosoftLayout}" useDefaultRowHighlightingRules="false">
      <highlight-word foregroundColor="DarkGreen" regex="^info" />
      <highlight-word foregroundColor="Yellow" regex="^warn" />
      <highlight-word foregroundColor="Black" backgroundColor="Red" regex="^fail" />
      <highlight-word foregroundColor="White" backgroundColor="Red" regex="^crit" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="console" />
  </rules>

</nlog>

Notice that the NLog ColoredConsole-Target is slower than the simple NLog Console-Target, because there is a huge overhead in changing colors (Still faster than AddConsole when using NLog ver. 4.7.1)

See also Hosting Lifetime Startup Messages in Console