How can I create a NLog Config Timeshift by hours in C#? - c#

How can I, if possible, create a log file with a timestamp that is shifted by x hours?
<variable name="logdt" value="${shortdate}"/>
<targets>
<target
name="file" xsi:type="File"
layout="${shortdate}${semi}${time}${semi}${message}"
fileName="${basedir}\logs\${logdt}**-6h**.csv"
archiveFileName="${basedir}\archives\${logdt}**-6h**.{#}.zip"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="7"
enableArchiveFileCompression="true"
keepFileOpen="true"
openFileCacheTimeout="30"
/>
</targets>

You can configure the Time Source.
https://github.com/NLog/NLog/wiki/Time-Source

Related

Nlog Logrotation, keep 7 days of logfiles than archive it every sunday

Is there a way to create a log rotation with NLOG that records a log for each day for seven days and then archives them after the seven days?
this is my current target with this i :
<target xsi:type="File"
name="error"
layout="${longdate} ${uppercase:${level}}: - ${message}"
fileName="${basedir}/logs/Error.log"
archiveFileName="${basedir}/logs/archive/Error{#}.zip"
archiveNumbering="Rolling"
enableArchiveFileCompression="true"
archiveEvery="Sunday"
archiveAboveSize="10000000"
maxArchiveDays ="28"
archiveDateFormat="yyyy-MM-dd"
concurrentWrites="false"/>
NLog likes to have single static file, but maybe this is possible:
<target xsi:type="File"
name="error"
layout="${longdate} ${uppercase:${level}}: - ${message}"
fileName="${basedir}/logs/Error.${date:format=ddd}.log"
archiveFileName="${basedir}/logs/archive/Error.{#}.zip"
archiveDateFormat="yyyy-MM-dd"
archiveNumbering="DateAndSequence"
archiveEvery="Day"
enableArchiveFileCompression="true"
archiveAboveSize="10000000"
maxArchiveDays ="28"
concurrentWrites="false"/>
Then ${basedir}/logs/-folder will grow to have 7 files:
Error.Mon.log
Error.Tue.log
Error.Wed.log
Error.Thu.log
Error.Fri.log
Error.Sat.log
Error.Sun.log
And when "rolling" to next file that already exists (ex. Error.Mon.log), then the old file will be moved to ${basedir}/logs/archive/-folder and renamed to Error.yyyy-MM-dd.log (Using timestamp of when the old file was created)
See also: https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples

Nlog not loggin to File

my nlog not creating files. I Use the same configuration in another project and everythink is Ok, but in new project nlog not create new files.
Nlog config :
<?xml version="1.0" encoding="utf-8" ?>
autoReload= "true"
internalLogLevel =" Trace"
internalLogFile ="c:\temp\internal-nlog.txt">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfile.txt"
/>
<target name="exceptions" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfileExceptions.txt"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<logger name="*" minlevel="Error" writeTo="exceptions" />
</rules>
On the console I can see that the log has been called but its not sent to a file.
I think the problem can be in c:\temp\internal-nlog.txt becouse this file has references to another project. And when i start another project internal-nlog.txt is update but when i start this project internal-nlog-txt doesnt update
Nlog action = content,
Copy to outputDirectory = copy if newer

How to configure NLog FileTarget to create sub-folder for each username?

I want to create custom folder and logs with Microsoft.Extensions.NLog with ILogger. I want each users in my system to his personal folder. I create a target like this.
<target xsi:type="File"
name="fileLog"
fileName="${basedir}/${userName}/${userName}.log"
maxArchiveFiles="50"
archiveAboveSize="10000000"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}| ${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}" />
And for example when I want to write a log userName to be transmited like argument.
Logger.LogError("Something went wrong. Id: {userName}", userName);
Thanks a lot for help!
I guess you can do this:
<nlog>
<variable name="UserName" layout="${event-properties:item=userName:whenEmpty=App}" />
<targets>
<target xsi:type="File"
name="fileLog"
fileName="${basedir}/${UserName}/${UserName}.log"
maxArchiveFiles="50"
archiveAboveSize="10000000"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}| ${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="fileLog" />
</rules>
</nlog>
Then you can do this:
Logger.LogError("Something went wrong. Id: {userName}", userName);
See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging
See also: https://github.com/NLog/NLog/wiki/Environment-User-Layout-Renderer
See also: https://github.com/NLog/NLog/wiki/AspNetUserIdentity-layout-renderer
See also: https://github.com/NLog/NLog/wiki/AspNet-User-Claim-layout-renderer

NLog missing log entries with async rollover file configuration

NLog didn't log every log messages with asynchronous rolling file logger configurations.
Following is my NLog.config xml.
<?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 async="true">
<target name="logfile" xsi:type="File" fileName="logs/log.txt"
maxArchiveFiles="10"
archiveAboveSize="1048576"
archiveNumbering="Sequence"
concurrentWrites="true"
archiveFileName="logs/log.{####}.txt"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
And the following is my code.
private static Logger log = LogManager.GetCurrentClassLogger();
Stopwatch sw = new Stopwatch();
public Form1()
{
InitializeComponent();
LogManager.ReconfigExistingLoggers();
}
private void button1_Click(object sender, EventArgs e)
{
string toLog;
sw.Start();
for (int i = 0; i < 100000; i++)
{
toLog = "Message:" + i.ToString();
log.Debug(toLog);
}
sw.Stop();
string s = "STOP :" + sw.Elapsed.ToString();
log.Debug(s);
}
I only get one file as the result and some log entries are missing. Following is the resulting log.txt file.
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11591
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11592
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11593
2015-10-16 12:04:08.9865|DEBUG|NLogAsync.Form1|Message:11594
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80436
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80437
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80438
2015-10-16 12:04:09.0802|DEBUG|NLogAsync.Form1|Message:80439
However when i remove the async attribute, the code is running properly.
<targets async="true"> is just a shorthand for wrapping all your targets with AsyncWrapper target. I.e. your configuration is equivalent to:
<targets>
<target name="logfile" xsi:type="AsyncWrapper">
<target xsi:type="File" fileName="logs/log.txt"
maxArchiveFiles="10"
archiveAboveSize="1048576"
archiveNumbering="Sequence"
concurrentWrites="true"
archiveFileName="logs/log.{####}.txt"/>
</target>
</targets>
This async wrapper will use default settings. Most important for you are queueLimit which is 10000 by default, and overflowAction which is Discard by default. What does it mean? After writer thread has more than 10000 log messages in queue all new log messages just discarded. So simplest way to make sure all your log messages will be processed is changing default overflowAction value to Grow. But you need to specify AsyncWrapper manually for that:
<targets>
<target name="logfile" xsi:type="AsyncWrapper" overflowAction="Grow">
<target xsi:type="File" fileName="logs/log.txt"
maxArchiveFiles="10"
archiveAboveSize="1048576"
archiveNumbering="Sequence"
concurrentWrites="true"
archiveFileName="logs/log.{####}.txt"/>
</target>
</targets>

Write records in descending order in NLog

I have a NLog configutation that writes to a file:
<targets>
<target name="file"
xsi:type="File"
layout="${longdate} | ${level} | ${message}"
fileName="${basedir}\logs\log.txt"
archiveFileName="${basedir}\logs\log.{#}.txt"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="7" />
</targets>
I want the most recent record to appear at the top of the txt file, so I don't have to scroll all the way to the bottom every time I open it since the logs can get very long. This seems like it should be in the configuration, but I'm not seeing it.
Any ideas?

Categories

Resources