My NLog is configured as follows
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File" fileName="${basedir}/log${shortdate}.txt" archiveAboveSize="500000" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="10" layout="${date:format=s}|${level}|${callsite}|${identity}|${message}|${exception:format=stacktrace}"/>
<!--<target name="console" xsi:type="Console" />-->
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
<!--<logger name="*" minlevel="Debug" writeTo="console" />-->
</rules>
</nlog>
But the stacktrace is not being logged when exception occurs. Is there a bug in NLog?
I have created a wrapper around Nlog and I am logging as follows
public void Error(string message, Exception ex)
{
logger.Error(message, ex);
}
I get the message in the log but not the stacktrace.
Thanks in advance
Try this in your layout:
${exception:format=ToString}
Have you tried using logger.ErrorException(message, ex); instead of logger.Error?
Related
I have a Graylog logging server set up for all our projects. One of the projects is using NLog and it uses a framework with Common Logging.
When the framework logs, the messsage received in Graylog is {0}. So somewhere it's string formatting not done.
If i configure a parameter and send in $(message) there, the expanded message is sent.
Also, the colored console configured works as expected.
<?xml version="1.0" encoding="utf-8" ?>
<nlog throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="NLog.Targets.GraylogHttp"/>
</extensions>
<targets>
<target name="graylog" xsi:type="GraylogHttp" facility="Superman"
graylogServer="http://xxxxxx.stackhero-network.com" graylogPort="xxxx">
<parameter name="real_message" layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" />
<parameter name="source_method" layout="${callsite}" />
</target>
<target name="coloredConsole" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" >
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" appendTo="graylog"/>
<logger name="*" minlevel="Trace" appendTo="coloredConsole"/>
</rules>
</nlog>
The code used for calling looks like this (Relevant parts...)
using Common.Logging;
internal static ILog Logger = LogManager.GetLogger<SboApp>();
Logger.Error($"UI Connect Error: {ex.Message}", ex);
I'm using
Common.Logging.NLog4412 v 3.4.1
NLog v 4.4.12
NLog.Targets.GraylogHttp v 0.0.24
What am i doing wrong
I have the following nlog.config file in ASP.NET Core 2.1 project. However, it's logging messages from every logger (including Microsoft logger) to console.
<?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"
autoReload="true"
internalLogLevel="Error"
internalLogFile="${specialfolder:folder=UserProfile}\nlog\internal-nlog.txt">
<variable name="fullLayout" value="${shortdate} [${uppercase:${level}}] ${logger}: ${message} ${exception:format=tostring} url: ${aspnet-request-url}" />
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write to console -->
<target name="console" xsi:type="ColoredConsole" layout="${fullLayout}" />
<!-- write to file -->
<target xsi:type="File"
name="allfile"
fileName="${defaultDirectory}/test-api-all.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-all-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File"
name="ownFile-web"
fileName="${defaultDirectory}/test-api-app.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-app-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="console" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
I do not have any logging settings in appsettings.json files. All logger configuration in in nlog.config. In the Program.cs, I'm registering NLog like:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging => logging.ClearProviders())
.UseNLog()
.Build();
How can I filter out Microsoft logs?
EDIT:
Above configuration started working without a problem the next day without me making any changes :O
Maybe this will work:
<!-- rules to map from logger name to target -->
<rules>
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
The order of the logging rules are important, as the rules are matched from the top. See also https://github.com/NLog/NLog/wiki/Configuration-file#rules
The order of your logging rules seems to be correct. I suggest trying to double check if your updated nlog.config file is being copied to the build directory (e.g. \bin\Debug\netcoreapp2.1\nlog.config)
I kind of encountered the same issue, but found out that debugging using Visual Studio, it sometimes doesn't really copy the nlog.config file to your build directory. So the solution is to Clean the project first, then Build, and finally Debug.
I have Logger of NLog package,
I want to define trace enable=true in my config logger file.
How can I do it?
My NLog.config file:
<?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">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
You do this by setting the minLevel attribute in your rules section of the NLog.config like so;
<rules>
<logger name="*" minlevel="Debug" writeTo="CSVFile" />
</rules>
Debug will write out Debug, Info, Warn, Error and Fatal-level log messages. Only Trace is skipped.
EDIT
Conversely, if you wanted to only log Trace, then set the maxLevel like so;
<rules>
<logger name="*" maxlevel="Trace" writeTo="CSVFile" />
</rules>
To just log a specific intermediate level, use minLevel and maxLevel together like;
<rules>
<logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="CSVFile" />
</rules>
EDIT2
I tweaked your config file such that the output logs to the console rather than the file;
<?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">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" writeTo="logconsole" />
</rules>
</nlog>
And when run in a test application where I'm writing out multiple logging levels like so;
_logger.Trace("trace text");
_logger.Debug("debug text");
_logger.Info("info text");
_logger.Warn("warn text");
_logger.Error("error text");
_logger.Fatal("fatal text");
And only the Trace text displays in the console window. One thing of note however, is that the XML in the config file must be correctly formatted. The sample above is working as described in my test application here.
You can create multiple levels of logging by creating multiple logger instaances such as
<rules>
<!-- add your logging rules here -->
<!-- different logger instances for different environments, no levels are mentioned explicitly, can be done if exclusion of some levels is required -->
<logger name="Log.Dev" minlevel="Debug" writeTo="database" enabled="true" />
<logger name="Log.Staging" minlevel="Info" writeTo="database" enabled="true" />
<logger name="Log.Production" minlevel="Error" writeTo="database" enabled="true" />
</rules>
After that while initializing give the name of the logger which you want to initialize
/// <summary>
/// The log.
/// Getting Logger instance from key name defined in Web.config of main web file. Key name is LoggerInstanceName
/// On the basis of name , logger instance and defined rules can be switched from one to another.
/// </summary>
private static readonly NLog.Logger Log = LogManager.GetLogger(Convert.ToString(ConfigurationManager.AppSettings.Get("LoggerInstance")));
Also do not forget to add key in your app settings
<appSettings>
<!--logger instance name-->
<add key="LoggerInstanceName" value="Log.Dev" />
</appSettings>
I use NLog for debugging/tracing in my app. What's happening is that I am seeing some extra stuff in the output. This is C#/VisualStudio on the Mac, targeting iOS.
Here is an example...
I'm using a target of type "Debugger", and my layout line is:
<layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
The call to the logger is:
log.Debug("Added New Key. Code = {0}", code);
And the output is:
AppleLibrary.PasswordMgr: 16:04:36.4064 Debug
AppleLibrary.PasswordMgr.SavePassword:55 Added New Key. Code = -34018
Every debug line starts with <logger name>:
Its even worse when I use a target type of "Console" with exactly the same layout. A call like this:
log.Debug("Started Application");
ends up with this:
2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589] 16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
in this case every line starts with: 2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589], which looks like the long date, logger name and thread/tick information.
Note that this does not happen with my file target, even though it uses exactly the same layout! The above call shows this in the logfile.txt:
16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
Which is exactly what I want.
Here is my 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" throwExceptions="true">
<targets>
<target name="logfile"
xsi:type="File"
header="############STARTING RUN ${date} ${time}"
archiveOldFileOnStartup="true"
maxArchiveFiles="5"
fileName="/Users/Paul/Dev/MyApp/MyApp.iOS/logfile.txt"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="console" xsi:type="Console"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="debugger"
xsi:type="Debugger"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
<logger name="CoreLibrary.*" minlevel="Trace" writeTo="debugger" enabled="false" />
<logger name="AppleLibrary.*" minlevel="Debug" writeTo="debugger" />
<logger name="MyApp.iOS.*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>
I'd appreciate any pointers as to what I'm misunderstanding here.
Thanks.
Paul.
I have some console apps I've written at work. I'd like to get NLog into them but I am having trouble.
When I inspect the 'logger' object, I see in it's 'Factory' property, that the configuration had targets=0, loggingrules=0, everything blank or unset.
So, it doesn't do ANYTHING.. doesn't drop an internal log file either... I have tried nLog.config NLog.config and nlog.config... to no avail. Tried ver 3 and 4 of NLog too...
Why would it not pick up the config?
I have:
NLog.config in the root with 'Content' for build action and 'Copy Always' set
Confirmed the NLog.config IS being copied to the bin
Here's the 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"
autoReload="true"
throwConfigExceptions="true"
throwExceptions="true"
internalLogLevel="Trace"
internalLogFile="c:\temp\NlogInternal.log"
internalLogToConsole="true"
internalLogToConsoleError="true"
internalLogToTrace="true">
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true" fileName="c:\temp\testlog.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
</nlog>
and finally (this doesn't error, but nothing is output since the config is blank):
private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("ConsoleApp test log...");
Do your app.config have a NLog configSection?
Something like this:
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
</nlog>
</configuration>
If even the internalLogger isn't working, you could debug the issue by setting
the InternalLogger.LogWriter
e.g.
// enable internal logging to a custom TextWriter
InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\\perl.txt")
I got the same issue on my end. When you make change your fileName Path "c:\temp\testlog.log" to
"c:/temp/testlog.log" then it will work. Hope the below snipet help you to resolve the issue.
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true"
fileName="c:/temp/testlog.log" layout="${longdate} ${uppercase:${level}}
${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>