Using the default configuration for LogEntries, is it possible to create insert parameterized values into the layout?
<nlog>
<extensions>
<add assembly="LogentriesNLog" />
</extensions>
<targets>
<target name="logentries" type="Logentries" debug="true" httpPut="false" ssl="false" layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} {SOME PARAM FROM CONFIG} : ${LEVEL}, ${message}">
</target>
</targets>
<rules>
<logger name="*" minLevel="Trace" appendTo="logentries" />
</rules>
</nlog>
I'm an idiot sometimes.
You can just stick them in the layout string
<target name="logentries" type="Logentries" debug="true" httpPut="false" ssl="false" layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} : ${LEVEL}, ${message}, ${SomeParam}"></target>
Related
I have a .NET Core application which has NLog configured. This is the contents of 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="false" internalLogLevel="Error" internalLogToConsole="true" internalLogIncludeTimestamp="true" keepVariablesOnReload="true">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="appId" value="" />
<variable name="componentId" value="" />
<variable name="file-target-path" value="" />
<variable name="file-target-name" value="" />
<targets>
<target xsi:type="Console" name="console-target" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\="${exception:format=tostring}"}" />
<target xsi:type="File" name="file-target"
layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\="${exception:format=tostring}"}"
fileName="${basedir}/${var:file-target-path}/${var:file-target-name}.log"
archiveFileName="${basedir}/${var:file-target-path}/${var:file-target-name}.{###}.txt"
archiveEvery="Day"
archiveNumbering="DateAndSequence"
archiveAboveSize="5242880"
archiveDateFormat="yyyyMMdd"
maxArchiveDays="31" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="console-target" />
<logger name="*" minLevel="Trace" writeTo="file-target" />
</rules>
</nlog>
I'm now writing a class which parses the log for a the Regex value \sApplication Running\s([\-]+?)\s. I currently have the log file path hard coded in my StreamReader like below:
Regex regex = new Regex(#"\sApplication Running\s([\-]+?)\s");
using (StreamReader reader = new StreamReader(#"C:\path\to\my\log_file.log"))
{
...
}
How can I update this so the log file is obtained from the logging configuration instead of the hard coding it in my class?
You can retrieve log file location from LogManager.Configuration.
var nlogFileTarget = LogManager.Configuration.AllTargets.OfType<FileTarget>().First();
var dummyEventInfo = new LogEventInfo { TimeStamp = DateTime.UtcNow };
var logFilePath = nlogFileTarget.FileName.Render(dummyEventInfo);
Similar solution:
<nlog>
<variable name="file-target-path" value="" />
<variable name="file-target-name" value="" />
<variable name="file-target-filename" value="${basedir}/${var:file-target-path}/${var:file-target-name}.log"" />
<targets>
<target xsi:type="File" name="file-target" fileName="${file-target-filename}" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="file-target" />
</rules>
</nlog>
And then you can do this:
var filetargetPath = NLog.LogManager.Configuration?.Variables["file-target-filename"]?.Render(LogEventInfo.CreateNullEvent());
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>
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?