To archive by file size when you’re using NLog, you can configure nlog.config 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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true">
<variable name ="logFile" value="C:/logs/servicelog-${shortdate}" />
<targets>
<target xsi:type="File"
name="mainLog"
fileName="${logFile}.log"
layout="${longdate} level=${level} message=${message}"
keepFileOpen ="false"
concurrentWrites ="true"
archiveNumbering="DateAndSequence"
archiveAboveSize="1000000"
maxArchiveFiles="10"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="mainLog" />
</rules>
</nlog>
Code language: HTML, XML (xml)
You specify archiveAboveSize in bytes. The above configuration is specifying ~1 MB.
When your log file hits the specified size, NLog will “archive” the file, which really just means it will rename the log file and start a new log file. It will rename the log file based on the setting archiveNumbering. It’s a good idea to set maxArchiveFiles as well, so you don’t run out of disk space.
Example of archiving by log file size
I’m logging to a log file with the short date in the name. The log file is called servicelog-2021-02-22.log.
Once servicelog-2021-02-22.log hits ~1 MB, NLog will rename servicelog-2021-02-22.log to servicelog-2021-02-22.20210222.0.log (because archiveNumbering=DateAndSequence) and then create a new file called servicelog-2021-02-22.log, like this:
Code language: plaintext (plaintext)servicelog-2021-02-22.log servicelog-2021-02-22.20210222.0.log
Let’s say I am logging all day and have 10 archived log files. Because maxArchiveFiles=10, when NLog has to archive again, it will delete the oldest archived file (servicelog-2021-02-22.20210222.0.log) and create the new archive log file with the next sequence number – servicelog-2021-02-22.20210222.10.log.
I’ll end up with the following log files:
Code language: plaintext (plaintext)servicelog-2021-02-22.log servicelog-2021-02-22.20210222.10.log servicelog-2021-02-22.20210222.9.log servicelog-2021-02-22.20210222.8.log servicelog-2021-02-22.20210222.7.log servicelog-2021-02-22.20210222.6.log servicelog-2021-02-22.20210222.5.log servicelog-2021-02-22.20210222.4.log servicelog-2021-02-22.20210222.3.log servicelog-2021-02-22.20210222.2.log servicelog-2021-02-22.20210222.1.log