22

I'm pretty new to NLog. I have a .NET framework console application using NLog. I hope to configure NLog to write the log to console directly. I installed NLog and the NLog.Config NuGet package, with the following content in nlog.config:

<?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"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
  <targets>
    <target xsi:type="Console"
            name="String"
            layout="Layout"
            footer="Layout"
            header="Layout"
            encoding="Encoding"
    />
  </targets>
</nlog>

Then in C#, the following two lines won't print to the console:

var logger = LogManager.GetCurrentClassLogger();
logger.Info("hello");

Looked online but didn't find anything so far.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
checai
  • 836
  • 4
  • 11
  • 17

2 Answers2

51

Check out the official tutorial here.

You need to add output rules:

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

Also simplify your console target:

<target name="console" xsi:type="Console" />

Many useful samples are here: Most useful NLog configurations

Pang
  • 9,564
  • 146
  • 81
  • 122
Alexey.Petriashev
  • 1,634
  • 1
  • 15
  • 19
  • How do you view the console when working in Visual Studio on a Web application. Which file menue > view > menu window? I have Output window open in Visual Studio > Show output from Debug, but nothing is logging. I am logging to a text file which is working fine. Thank you. – Moojjoo May 04 '20 at 18:24
  • launch it as console (select in combobox near Start) – Alexey.Petriashev May 14 '20 at 10:55
9

You can configure from code as well:

var config = new NLog.Config.LoggingConfiguration();

// Targets where to log to: Console
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

// Rules for mapping loggers to targets
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);

// Apply config
NLog.LogManager.Configuration = config;

Use:

var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("hello");
Pang
  • 9,564
  • 146
  • 81
  • 122
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162