NLog per session - nlog

Is there any way to configure NLog to log information per application session? As of now it appends the messages in the log file each time application is executed (WinForm). What we'd like to have is to only store the info of the current session. Meaning that when application launches, all previous messages are cleared before any new message is logged. This way only the messages of current sessions will be available in the log file.
Here is the current configuration
<?xml version="1.0"?>
<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="FileTarget" xsi:type="File" fileName="MainLogFile.txt" layout="${longdate} ${callsite} ${level} ${message}"/>/>
</targets>
<rules>
<logger name="*" levels="Trace,Info,Warn,Error,Debug,Fatal" writeTo="FileTarget"/>
</rules>
</nlog>
Thanks

Assuming that you can only have one instance of your application open at once, you can just use the deleteOldFileOnStartup parameter:
<targets>
<target name="FileTarget" xsi:type="File" fileName="MainLogFile.txt" layout="${longdate} ${callsite} ${level} ${message}" deleteOldFileOnStartup="true">
</targets>

Related

NLog - Daily Log file - how to add a summary when it's triggered or new log file is created

I have the config setup for daily logging. (I assume the following is correct). How can add a 'summary' when the new log file is created. I'd like to add a daily 'count' to the last line in the log file for the day. Is this possible? How do I know when the new log is triggered?
<variable name="logDirectory" value="C:/Logs/" />
<targets async="true">
<target xsi:type="File"
name="ErrorLog"
filename="${logDirectory}PDF.log"
archiveFileName="log.{#}.log"
archiveNumbering="Date"
archiveEvery="Day"
archiveDateFormat="yyyyMMdd" />
NLog FileTarget has support for Footer-layout and Header-Layout.
If you need special statistics then you probably need to write your owned custom layout-renderer.
<nlog>
<targets>
<target name="ErrorLog" xsi:type="File"
header="----------------- Logging started on ${longdate} ------------------"
footer="----------------- Logging finished on ${longdate} -----------------"
filename="${logDirectory}PDF.log"
archiveFileName="log.{#}.log"
archiveNumbering="Date"
archiveEvery="Day"
archiveDateFormat="yyyyMMdd" />
</targets>
<rules>
<logger name="*" minlevel="Error" writeTo="ErrorLog" />
</rules>
</nlog>

Can layout render(s) be used for FileName(s)?

Can layout render(s) (processname to be exact) be used for FileName(s)?
Note,
the internalLogFile (and INTERNAL.log value)
and
fileName="${processname}.NLog.${shortdate}.PeanutButter.log"
values below.
<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="${processname}.NLog.INTERNAL.log"
internalLogLevel="Trace" >
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="target1" fileName="${processname}.NLog.${shortdate}.PeanutButter.log"
layout="${date}|${level:uppercase=true}|${logger}|${environment-user:userName=true:domain=true}|****|${message} ${exception:format=toString,Data}|${all-event-properties}" />
<target xsi:type="Console" name="target2"
layout="${date}|${level:uppercase=true}|${logger}|${message} ${exception:format=toString,Data}|${all-event-properties}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Trace" writeTo="target1,target2" />
</rules>
</nlog>
With the above, I'm getting a file created:
${processname}.NLog.INTERNAL.log
(literally, that is the filename)
and no files at all named:
*PeanutButter.log
where * is a wild card search.
Imported packages below.
<ItemGroup>
<PackageReference Include="NLog" Version="4.6.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
</ItemGroup>
Can layout render(s) (processname to be exact) be used for FileName(s)?
Filetarget
Yes, it's fully supported for the file target.
See this simple example from the Filetarget docs:
Per-level log files
Single File target can be used to write to multiple files at once.
The following configuration will cause log entries for each log level
to be written to a separate file, so you will get:
Trace.log
Debug.log
Info.log
Warn.log
Error.log
Fatal.log
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="${basedir}/${level}.log" />
Internal logger
${processname}.NLog.INTERNAL.log
(literally, that is the filename)
It's not supported for the internal logger filename!
From the Internalloger docs
internalLogFile
Note: only a few layouts are supported, as the internal log needs to be as stable as possible.
NLog 4.6+: Supported renderers (without options): ${currentdir}, ${basedir}, ${tempdir}
NLog 4.6+: Environment Variables are also supported: e.g. %appdata%
If the internal logger would fail because of (complicated) layout renderers, where should it log that then? ;)

I dont want nlog to create log file for every millisec

Im using the following config . This creates log file for every milli sec.
I want only one log file per execution and it should be time stamped
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<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="C:\log\log- ${date:format=dd/MM/yyyy HH\:mm\:ss}.txt"></target>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
The only way to do this is to set the fileName programmatically.
E.g.
var logfileTarget = NLog.LogManager.Configuration.FindTargetByName<FileTarget>("logfile");
logfileTarget.FileName = "filename_with_date_and_ext"; //you can use layout renderers here.
See API docs
Have submitted a PR for the processinfo-layout-renderer, so it can output process-start-time in the wanted format. But it only supports local-time
fileName="C:\log\log-${processinfo:property=StartTime:format=yyyy-MM-dd_HHmmss}.log"

Transform that preserve namespace prefixes

I'm trying to insert an NLog custom config section into my Web.config using this XDT section:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" throwExceptions="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xdt:Transform="InsertIfMissing" >
<targets>
<target xsi:type="File" name="logfile" fileName="H:\testLog.txt" layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
When I run the XDT transform, my Web.Debug.config contains:
<nlog throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
<targets>
<target d4p1:type="File" name="logfile" fileName="H:\testLog.txt" layout="${longdate} ${uppercase:${level}} ${message}" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
Typically, a namespace prefix is arbitrary, so transforming xsi to d4p1 would cause no issues.
However, I get a runtime exception in my application from NLog when I use d4p1. Manually changing the instances of d4p1 to xsi fixes the issue, but it subverts the utility of config transformation for me if the user needs to manually alter the file afterward.
Is there a way to preserve namespace prefixes using XDT?
We had exactly the same issue. I'm not sure why it suddenly started happening with a particular project, but the solution for us was to add the xsi namespace to the top level of the original configuration file (ie the base file the transformations work on). So...
<configuration>
... would become...
<configuration xmlns:xsi="http://www.nlog-project.org/schemas/NLog.xsd">
This did the trick.
An alternative approach that also worked was to apply the transforms on child elements of the nlog element.
Hope that helps someone.
I started to see this problem when I moved my xdt:Transform attribute from the target and rule tags to nlog. Moving them back to the original tags like this solved it:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" throwExceptions="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets xdt:Transform="InsertIfMissing">
<target xsi:type="File" name="logfile" fileName="H:\testLog.txt" layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules xdt:Transform="InsertIfMissing">
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>

Configuring NLog E-Mail Message Body Output

I am using NLog v2 Beta to log a VB.NET .DLL which creates and sends messages to a third party service. I have it working perfectly when logging to a file, but now want it to also e-mail me the errors it catches automatically. The following is the relevant bit of 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="papercut" xsi:type="BufferingWrapper" bufferSize="100">
<target xsi:type="PostFilteringWrapper" defaultFilter="level >= LogLevel.Debug">
<target xsi:type="Mail"
name="papercut"
subject="Your app has errors"
to="ToAddress#Domain.com"
from="FromAddress#Domain.com"
smtpServer="127.0.0.1"
smtpPort="25"
body={longdate}|{message} />
</target>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="papercut" />
</rules>
</nlog>
By default it will just list the logged message in the e-mail body. I want to preceed this with the date / time logged, so have been playing around with the body= part to no avail (it either doesn't evaluate the variables properly or crashes NLog). Can somebody please give me a pointer as to how to configure NLog to do this?
seems like you are missing $ in the body configuration and that might be the reason that NLog is crashing..
body = "${longdate}| ${message}"
more info regarding Mail target
https://github.com/NLog/NLog/wiki/Mail-target
also you can enable logging for NLog errors itself as below..
<nlog
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true"
internalLogFile="Nloglog.log"
internalLogLevel="Warn"
>
.....
</nlog>

Resources