I´ve got a Windows-Service which runs in the same location as its Notify. They communicate with WebSocketSharp.
But only one program has a log file. I think the problem is, the notify consumes the nlog.config at first and for the service the nlog.config is locked. But I may confuse it. Also always the Notify only produces the log, never the service. May be in my nlog.config is an error? But then why does the notify produce one but the Service not, when the service and the notify should use the same?
I've tested and the service does not produce any log, even the notify is not running.
May there be a problem with Windows Service and NLog?
Here 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">
<time type="AccurateUtc" />
<targets>
<target name="debug-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/MyService/log/${date:format=yyyy-MM}.log" layout="${longdate} | ${level} | ${message}" />
<target name="trace-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/MyService/log/trace/${date:format=yyyy-MM-dd}.log" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fffffff} | ${level} | ${message}" />
<target name="errorfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/MyService/log/Error.log" layout="${longdate} | ${level} | ${message}" />
<target name="console" xsi:type="Console" layout="${longdate} | ${level} | ${callsite} | ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="trace-logfile" />
<logger name="*" minlevel="Debug" writeTo="debug-logfile" />
<logger name="*" minlevel="Error" writeTo="errorfile" />
</rules>
</nlog>
Here is how I use NLog:
protected static NLog.Logger Log = LogManager.GetCurrentClassLogger();
Log.Trace("Message");
Related
I am using CKFinder in ASP.NET. It has been working but has recently stopped (uploads specifically). While trying to track down the issues, I noticed no logs are being written.
In my web.config, I have enabled verbose logging for ckfinder:
enableVerboseLogging="true"
Here is my NLog.config file (which I am not familiar with; we use log4net). Other traces are being written via NLog, however, so I think this is correct.
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target xsi:type="File" name="logFile" fileName="${basedir}/App_Data/logs/ckfinder.log"
archiveFileName="${basedir}/App_Data/logs/archives/ckfinder.{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="5" concurrentWrites="true" keepFileOpen="false"
layout="${level} | ${logger} | ${longdate} | ${message}${onexception: | ${exception:format=ToString,StackTrace:maxInnerExceptionLevel=10}}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
I was forgetting this line from Startup.Configuration:
LoggerManager.LoggerAdapterFactory = new NLogLoggerAdapterFactory();
I have the following NLog config file below. It's set to Archive every day and initially I had just the MaxArchiveFiles. Now I would like to keep only X amount of days of archived files and found the info that says MaxArchiveDays is available in v4.7 and up. So, I upgraded to v4.7 but now it doesn't seem to archive either on Days or File number.
Anyone see anything wrong with this config file with NLog v4.7?
<?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"
throwExceptions="true">
<variable name="LogDirectory" value="D:/Logs/HRImport"/>
<targets async="true">
<target name="DefaultTarget"
xsi:type="File"
fileName="${LogDirectory}/LogFile.log"
encoding="utf-8"
layout="${longdate} | ${callsite} | ${message}"
archiveFileName="${LogDirectory}/Archive/${shortdate}_log.{#}.log"
archiveAboveSize="3145728"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="3"
maxArchiveDays="2"
/>
<!--1 meg: 1048576 -->
<target name="ConsoleTarget"
xsi:type="Console"
layout="${longdate} ${logger:shortName=True} ${message}${onexception:EXCEPTION OCCURRED\:${exception:format=type,message,StackTrace,method:maxInnerExceptionLevel=8:innerFormat=type,message,StackTrace,method}}"
/>
</targets>
<rules>
<logger name="defaultLogger" minlevel="Debug" writeTo="DefaultTarget,ConsoleTarget" />
</rules>
</nlog>
** UPDATE **
<target name="DefaultTarget"
xsi:type="File"
fileName="${LogDirectory}/LogFile.log"
encoding="utf-8"
layout="${longdate} | ${callsite} | ${message}"
archiveFileName="${LogDirectory}/Archive/{#}_log.log"
archiveNumbering="DateAndSequence"
archiveAboveSize="3145728"
archiveEvery="Day"
maxArchiveFiles="3"
maxArchiveDays="2"
/>
The problem is the use of ${shortdate}:
archiveFileName="${LogDirectory}/Archive/${shortdate}_log.{#}.log"
archiveNumbering="Rolling"
When using Layout in archiveFileName then it must be very static. Only {#} should contain the dynamic part.
Instead try this:
archiveFileName="${LogDirectory}/Archive/{#}_log.log"
archiveNumbering="DateAndSequence"
See also: https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples
I have an application which runs many threads (~50), every thread acquires a payment with lock to be processed from a database, and then processes it.
However, 50 threads make logs unreadable, mixed up and of enormous filesize.
Now, I want to make NLog write to a separate file for every payment ID, so that all history on payment processment is stored in one file.
NLog configuration 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="file" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
<target name="f" xsi:type="File" fileName="C:\LogFiles\Immediate\${shortdate}.server.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file"/>
</rules>
</nlog>
My code now:
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); // "2017-07-20.log"
while (!_cancellationToken.IsCancellationRequested)
{
using (var session = _connectionFactory.GetSession())
{
AcquirePaymentWithUpdlockReadpast(session,
Logger, // "2017-07-20.log"
payment => {
if (payment == null)
return;
Logger.Debug($"Payment {payment.Id} has been acquired for processment");
ProcessPayment(session, Logger, payment); // "2017-07-20.log"
});
}
Thread.Sleep(50);
}
What I expect it to be:
private static readonly ILogger GeneralLogger = LogManager.GetCurrentClassLogger(); // "2017-07-20.General.log"
while (!_cancellationToken.IsCancellationRequested)
{
using (var session = _connectionFactory.GetSession())
{
AcquirePaymentWithUpdlockReadpast(session,
GeneralLogger, // "2017-07-20.General.log"
payment => {
if (payment == null)
return;
var paymentLogger = LogManager.GetCurrentClassLogger();
paymentLogger.FileName = $"Payment-{payment.Id}.log"; // <-- I want this.
paymentLogger.Debug($"Payment has been acquired for processment");
ProcessPayment(session, paymentLogger, payment); // "2017-07-20.Payment-123.log"
});
}
Thread.Sleep(50);
}
I have found some solutions which use LogManager.Configuration, but it doesn't seem to be thread-safe.
Maybe something like this:
<?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="file" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
<target name="f" xsi:type="File" fileName="C:\LogFiles\Immediate\${shortdate}.server.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
</target>
<target name="paymentFile" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
<target name="p" xsi:type="File" fileName="C:\LogFiles\Immediate\Payment-${event-properties:PaymentID:whenEmpty=0}.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="paymentFile">
<condition="'${event-properties:PaymentID:whenEmpty=0}'!='0'" action="LogFinal" />
</logger>
<logger name="*" minlevel="Debug" writeTo="file"/>
</rules>
</nlog>
Then you can do the logging like this (Can be improved with NLog-Fluent):
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, $"Payment has been acquired for processment");
theEvent.Properties["PaymentID"] = payment.Id;
Logger.Debug(theEvent);
Alternative solution could be like this:
var paymentLogger = LogManager.GetLogger($"Payment-{payment.Id}");
paymentLogger.Debug($"Payment has been acquired for processment")
And then change the logger-filter to this:
<logger name="Payment-*" minlevel="Debug" writeTo="paymentFile" />
And then change paymentFile filename to this:
fileName="C:\LogFiles\Immediate\{logger}.log"
Thanks to Rolf Kristensen's answer, I have used the second approach, but have found a similar, but shorter solution which uses name property:
<?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="all" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
<target name="f" xsi:type="File" fileName="C:\LogFiles\${shortdate}.All.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
</target>
<target name="perLoggerName" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
<target name="f" xsi:type="File" fileName="C:\LogFiles\${shortdate}.${logger}.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="all"/>
<logger name="Document-*" minlevel="Debug" writeTo="perLoggerName"/>
<logger name="Job-*" minlevel="Debug" writeTo="perLoggerName"/>
</rules>
</nlog>
I'm trying to configure NLog for my C# application. I've got the logging working but it seems to have a mind of it's own in regards to whitespace. 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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
<variable name="brief"
value="${longdate} | ${level} | ${logger} |: ${message}" />
<variable name="verbose"
value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} |: ${message}" />
<targets>
<target name="myLog" xsi:type="File" fileName="myLog.txt" layout="${verbose}" />
<target name="console" xsi:type="Console" layout="${brief}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="myLog" />
<logger name="*" minlevel="Info" writeTo="console" />
</rules>
</nlog>
The log's output currently looks like this:
2016-05-19 12:08:00.0302|DEBUG|Namespace.ClassName|:Some log message here...
For some reason, NLog is getting rid of the spaces I defined in the target's layout attribute. What I would like the log entry to look like is:
2016-05-19 12:08:00.0302 | DEBUG | Namespace.ClassName |: Some log message here...
How do I get NLog to preserve the spaces in the layout attribute?
I've also tried to set the level to a fixed length with padding like this: ${padding:padding=5,fixedlength=true:${level:uppercase=true}} as mentioned in this post, but still no luck.
I discovered that NLog doesn't play nice when there is a # character in the path for the solution. Renamed the path and it started working again.
This sounds trivial, but I somehow cannot manage to do it. I have the below 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" throwExceptions="true">
<variable name="logDirectory" value="${basedir}/App_Data/logs"/>
<targets>
<target name="file" xsi:type="AsyncWrapper">
<target xsi:type="File" name="f1" fileName="${logDirectory}\log1.txt" layout="${longdate} ${callsite} ${level} ${message} (File 1)"/>
</target>
<target xsi:type="File" name="fileGeneral" fileName="${logDirectory}\log_${shortdate}.txt" >
<layout xsi:type="Log4JXmlEventLayout"/>
</target>
<target xsi:type="File" name="fileRaven" fileName="${logDirectory}\raven_${shortdate}.txt" >
<layout xsi:type="Log4JXmlEventLayout"/>
</target>
</targets>
<rules>
<logger name="Raven.*" minlevel="Trace" writeTo="fileRaven"></logger>
<logger name="*" minlevel="Trace" writeTo="fileGeneral"></logger>
</rules>
</nlog>
This is ending up with Raven + ALL logs to 'log_[date].txt', and another copy of just RavenDB logs in 'raven_[date].txt'. How should this be done?
<logger name="Raven.*" minlevel="Trace" writeTo="fileRaven" final="true"></logger>
Where final="true" means that no more rules for Raven.* will be executed will do what you are asking (if I understood you correctly).
Unfortunately this is not possible.
The reason is that the loggers are evaluated from top to bottom, the first one matching will be used, and does below will not be evaluated.
In you case this means that when logging anything Raven related the first logger will be used and stops the flow.