Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have NLog write to console

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.

like image 978
checai Avatar asked Jun 15 '18 21:06

checai


People also ask

How do you write an NLog?

Configuration in C# using NLog; using NLog. Config; using NLog. Targets; ... var config = new LoggingConfiguration(); var consoleTarget = new ConsoleTarget { Name = "console", Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}", }; config.

Where does NLog write to by default?

By default, the web. nlog file can be found at: C:\Program Files (x86)\Pleasant Solutions\Pleasant Password Server\www\web.

What is NLog writing?

NLog is a flexible and free logging platform for various . NET platforms, including . NET standard. NLog makes it easy to write to several targets. (database, file, console) and change the logging configuration on-the-fly.


2 Answers

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

like image 99
Alexey.Petriashev Avatar answered Oct 10 '22 23:10

Alexey.Petriashev


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");
like image 44
Mariusz Jamro Avatar answered Oct 10 '22 22:10

Mariusz Jamro