Skip to content

NLog Console and AddConsole

Rolf Kristensen edited this page Nov 18, 2024 · 7 revisions

NLog Console vs AddConsole

The Microsoft AddConsole is asynchronous by default, but the console is still very slow (Takes 10 secs to write 50.000 msgs). 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}${when:when=level==LogLevel.Trace:inner=trce}" />
  <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" text="info" wholeWords="true" />
      <highlight-word foregroundColor="Yellow" text="warn" wholeWords="true" />
      <highlight-word foregroundColor="Black" backgroundColor="Red" text="fail" wholeWords="true" />
      <highlight-word foregroundColor="White" backgroundColor="Red" text="crit" wholeWords="true" />
    </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, but only if using <targets async="true">)

Notice that NLog Console-Target has the option WriteBuffer, that will double its output performance when combined with <targets async="true">.

Notice that NLog.Extensions.Logging v1.7.5 introduces the layout-renderer ${MicrosoftConsoleLayout}, so one can replace the NLog config variables ${MicrosoftLayout} + ${MicrosoftLevel} with that.

See also Hosting Lifetime Startup Messages in Console