NLog – Log to console

There are two configuration options for logging to the console when you’re using NLog:

  1. Console target – uses the default text colors.
  2. ColoredConsole target – allows you to configure the color of logging messages.

In this article, I’ll show how to configure these two targets using nlog.config. At the end, I’ll show an example of configuring NLog programmatically.

Console target

Add a Console target and a rule that writes to that target in nlog.config, like this:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false">


  <variable name ="logFile" value="C:/logs/helloworld-${shortdate}" />

  <targets>
    <target xsi:type="File"
            name="fileTarget"
            fileName="C:/logs/helloworld-${shortdate}.log"
            layout="${longdate} level=${level} message=${message}"
            keepFileOpen ="false"
            concurrentWrites ="true"/>

    <target name="consoleTarget" xsi:type="Console" layout="${longdate} level=${level} message=${message}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="fileTarget" />
    <logger name="*" minlevel="Trace" writeTo="consoleTarget" />
  </rules>

</nlog>
Code language: HTML, XML (xml)

I’ll run the following code to show what this console logging configuration looks like:

var logger = LogManager.GetCurrentClassLogger();

logger.Info("Starting now");

for(int i = 0; i < 15; i++)
{
	if (i % 15 == 0)
	{
		logger.Trace($"{i} is divisible by 15");
	}
	else if (i % 5 == 0)
	{
		logger.Debug($"{i} is divisible by 5");
	}
	else if (i % 3 == 0)
	{
		logger.Error($"{i} is divisible by 3");
	}
	else if (i % 2 == 0)
	{
		logger.Warn($"{i} is even");
	}

}
Code language: C# (cs)

Running the console app outputs the following logging messages to the console:

2021-05-08 09:09:42.2990 level=Info message=Starting now
2021-05-08 09:09:42.3427 level=Trace message=0 is divisible by 15
2021-05-08 09:09:42.3427 level=Warn message=2 is even
2021-05-08 09:09:42.3427 level=Error message=3 is divisible by 3
2021-05-08 09:09:42.3427 level=Warn message=4 is even
2021-05-08 09:09:42.3427 level=Debug message=5 is divisible by 5
2021-05-08 09:09:42.3427 level=Error message=6 is divisible by 3
2021-05-08 09:09:42.3427 level=Warn message=8 is even
2021-05-08 09:09:42.3427 level=Error message=9 is divisible by 3
2021-05-08 09:09:42.3427 level=Debug message=10 is divisible by 5
2021-05-08 09:09:42.3427 level=Error message=12 is divisible by 3
2021-05-08 09:09:42.3427 level=Warn message=14 is evenCode language: plaintext (plaintext)

Note: The same log messages are simultaneously logged in C:\logs\helloworld-2021-05-07.log.

ColoredConsole target – change the color of logging messages

Instead of showing the default console text color for all logging messages, you can use the ColoredConsole target to customize how the text should appear. You can change the text color and background color per logging level. You can even highlight specific words.

To configure this option, add the ColoredConsole target and add a rule to write to this target. Optionally you can add in highlight-word and highlight-row settings to override the default NLog colors.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false">


  <variable name ="logFile" value="C:/logs/helloworld-${shortdate}" />

  <targets>
    <target xsi:type="File"
            name="fileTarget"
            fileName="C:/logs/helloworld-${shortdate}.log"
            layout="${longdate} level=${level} message=${message}"
            keepFileOpen ="false"
            concurrentWrites ="true"/>

    <target name="consoleTarget" xsi:type="ColoredConsole" layout="${longdate} level=${level} message=${message}">
      <highlight-word foregroundColor="Green" regex="Hello World"/>
      <highlight-row condition="level == LogLevel.Trace" foregroundColor="NoChange" />
      <highlight-row condition="level == LogLevel.Debug" foregroundColor="NoChange" />
      <highlight-row condition="level == LogLevel.Info" foregroundColor="NoChange" />
      <highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
      <highlight-row condition="level == LogLevel.Error" foregroundColor="NoChange" backgroundColor="DarkRed" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="fileTarget" />
    <logger name="*" minlevel="Trace" writeTo="consoleTarget" />
  </rules>

</nlog>
Code language: HTML, XML (xml)

I’ll run the following code to show this logging configuration in action:

var logger = LogManager.GetCurrentClassLogger();

logger.Info("Hello World");
logger.Warn("You'll probably ignore this");
logger.Debug("Debugging message");
logger.Trace("This is a trace message");
logger.Error("Ran into an error");
Code language: C# (cs)

This outputs the following to the console:

Nlog ColoredConsole showing logging messages with different colors

Note: The same log messages (but not the color-coding) are simultaneously logged in C:\logs\helloworld-2021-05-07.log.

Configure console logging programmatically

The most common way to configure logging is by using the config file. But you can also configure logging programmatically if you wish to do so.

To configure console logging programmatically, you have to add a rule and pass in a ConsoleTarget (or ColoredConsoleTarget) object, like this:

using NLog;
using NLog.Config;
using NLog.Targets;

static void Main(string[] args)
{
	var nlogConfig = new LoggingConfiguration();

	nlogConfig.AddRule(minLevel: LogLevel.Trace, maxLevel: LogLevel.Fatal, 
		target: new ConsoleTarget("consoleTarget") 
		{
			Layout = "${longdate} level=${level} message=${message}"
		});

	LogManager.Configuration = nlogConfig;

	var logger = LogManager.GetCurrentClassLogger();
	logger.Info("Info message");
	logger.Warn("Warn message");
	logger.Debug("Debugging message");
	logger.Trace("Trace message");
	logger.Error("Error message");
}

Code language: C# (cs)

Note: The ConsoleTarget.Layout property can accept a string, as shown above. The layout string is the same format that you’d add if you were using nlog.config.

Running this results in the following output to console:

2021-05-08 09:01:21.6007 level=Info message=Info message
2021-05-08 09:01:21.6175 level=Warn message=Warn message
2021-05-08 09:01:21.6175 level=Debug message=Debugging message
2021-05-08 09:01:21.6175 level=Trace message=Trace message
2021-05-08 09:01:21.6175 level=Error message=Error messageCode language: plaintext (plaintext)