File target
If you want to contribute, please create a user account and contact Jarek to get edit access.
Contents |
Usage
Writes log messages to one or more files.
Supported in



Configuration Syntax
<target xsi:type="File"
name="String"
layout="Layout"
header="Layout"
footer="Layout"
encoding="Encoding"
lineEnding="Enum"
archiveAboveSize="Long"
maxArchiveFiles="Integer"
archiveFileName="Layout"
archiveNumbering="Enum"
archiveEvery="Enum"
replaceFileContentsOnEachWrite="Boolean"
fileAttributes="Enum"
fileName="Layout"
deleteOldFileOnStartup="Boolean"
enableFileDelete="Boolean"
createDirs="Boolean"
concurrentWrites="Boolean"
openFileCacheTimeout="Integer"
openFileCacheSize="Integer"
networkWrites="Boolean"
concurrentWriteAttemptDelay="Integer"
concurrentWriteAttempts="Integer"
bufferSize="Integer"
autoFlush="Boolean"
keepFileOpen="Boolean" />
</targets>
Parameters
- General Options
- name - Name of the target.
- Layout Options
- layout - Text to be rendered.Layout Required. Default: ${longdate}|${level:uppercase=true}|${logger}|${message}
- header - Header.Layout
- footer - Footer.Layout
- encoding - File encoding.Encoding
- lineEnding - Line ending mode.
Possible values: - Archival Options
- archiveAboveSize - Size in bytes above which log files will be automatically archived.LongCaution: Enabling this option can considerably slow down your file logging in multi-process scenarios. If only one process is going to be writing to the file, consider setting
ConcurrentWrites tofalse for maximum performance. - maxArchiveFiles - Maximum number of archive files that should be kept.Integer Default: 9
- archiveFileName - Name of the file to be used for an archive.LayoutIt may contain a special placeholder {#####} that will be replaced with a sequence of numbers depending on the archiving strategy. The number of hash characters used determines the number of numerical digits to be used for numbering files.
- archiveNumbering - Way file archives are numbered.
Possible values: - archiveEvery - Indicates whether to automatically archive log files every time the specified time passes.
Possible values:Files are moved to the archive as part of the write operation if the current period of time changes. For example if the currenthour changes from 10 to 11, the first write that will occur on or after 11:00 will trigger the archiving. Caution: Enabling this option can considerably slow down your file logging in multi-process scenarios. If only one process is going to be writing to the file, consider settingConcurrentWrites tofalse for maximum performance. - Output Options
- replaceFileContentsOnEachWrite - Indicates whether to replace file contents on each write instead of appending log message at the end.Boolean Default: False
- fileAttributes - File attributes (Windows only).
Possible values:This parameter is not supported in:
- NLog v1.0 for .NET Compact Framework 1.0
- NLog v1.0 for .NET Compact Framework 2.0
- NLog v2.0 for .NET Compact Framework 2.0
- NLog v2.0 for .NET Compact Framework 3.5
- NLog v2.0 for Silverlight 4.0
- fileName - Name of the file to write to.Layout Required.This FileName string is a layout which may include instances of layout renderers. This lets you use a single target to write to multiple files.
The following value makes NLog write logging events to files based on the log level in the directory where the application runs. ${basedir}/${level}.log AllDebug messages will go toDebug.log , allInfo messages will go toInfo.log and so on. You can combine as many of the layout renderers as you want to produce an arbitrary log file name. - deleteOldFileOnStartup - Indicates whether to delete old log file on startup.Boolean Default: FalseThis option works only when the "FileName" parameter denotes a single file.
- enableFileDelete - Indicates whether to enable log file(s) to be deleted.Boolean Default: True
- createDirs - Indicates whether to create directories if they don't exist.Boolean Default: TrueSetting this to false may improve performance a bit, but you'll receive an error when attempting to write to a directory that's not present.
- Performance Tuning Options
- concurrentWrites - Indicates whether concurrent writes to the log file by multiple processes on the same host.Boolean Default: TrueThis makes multi-process logging possible. NLog uses a special technique that lets it keep the files open for writing.
- openFileCacheTimeout - Maximum number of seconds that files are kept open. If this number is negative the files are not automatically closed after a period of inactivity.Integer Default: -1
- openFileCacheSize - Number of files to be kept open. Setting this to a higher value may improve performance in a situation where a single File target is writing to many files (such as splitting by level or by logger).Integer Default: 5The files are managed on a LRU (least recently used) basis, which flushes the files that have not been used for the longest period of time should the cache become full. As a rule of thumb, you shouldn't set this parameter to a very high value. A number like 10-15 shouldn't be exceeded, because you'd be keeping a large number of files open which consumes system resources.
- networkWrites - Indicates whether concurrent writes to the log file by multiple processes on different network hosts.Boolean Default: FalseThis effectively prevents files from being kept open.
- concurrentWriteAttemptDelay - Delay in milliseconds to wait before attempting to write to the file again.Integer Default: 1The actual delay is a random value between 0 and the value specified in this parameter. On each failed attempt the delay base is doubled up to ConcurrentWriteAttempts times.
Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be: a random value between 0 and 10 milliseconds - 1st attempt a random value between 0 and 20 milliseconds - 2nd attempt a random value between 0 and 40 milliseconds - 3rd attempt a random value between 0 and 80 milliseconds - 4th attempt ... and so on. - concurrentWriteAttempts - Number of times the write is appended on the file before NLog discards the log message.Integer Default: 10
- bufferSize - Log file buffer size in bytes.Integer Default: 32768
- autoFlush - Indicates whether to automatically flush the file buffers after each log message.Boolean Default: True
- keepFileOpen - Indicates whether to keep log file open instead of opening and closing it on each logging event.Boolean Default: FalseSetting this property to
True helps improve performance.
Examples
Simple logging
The simplest use of File target is to produce single log file. In order to do this, put the following code in the configuration file such as NLog.config. Logs wil be written to logfile.txt in logs directory.
<?xml version="1.0" ?> <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" layout="${longdate} ${logger} ${message}" fileName="${basedir}/logs/logfile.txt" keepFileOpen="false" encoding="iso-8859-2" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
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
<?xml version="1.0" ?> <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" layout="${longdate} ${logger} ${message}" fileName="${basedir}/${level}.log" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
One log file per day
The following configuration will create one log file for each day. Log files will be named:
- 2010-06-05.log
- 2010-06-06.log
- 2010-06-07.log
- 2010-06-08.log
...
<?xml version="1.0" ?> <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" layout="${longdate} ${logger} ${message}" fileName="${basedir}/${shortdate}.log" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
Asynchronous logging
Depending on your usage scenario it may be useful to add an AsyncWrapper target the file target. This way all your log messages will be written on a separate thread so your main thread can be unblocked more quickly. Asynchronous logging is recommended for multi-threaded server applications which run for a long time and is not recommended for quickly-finishing command line applications.
<?xml version="1.0" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <!-- Log in a separate thread, possibly queueing up to 5000 messages. When the queue overflows, discard any extra messages--> <target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard"> <target xsi:type="File" fileName="${basedir}/logs/${level}.txt" /> </target> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
Creating comma-separated log file (CSV)
In order to create comma-separated files (CSV), use the following configuration, which utilizes CsvLayout. The resulting file will have 4 columns and will be formatted according to CSV rules:
<?xml version="1.0" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="csv" xsi:type="File" fileName="${basedir}/file.csv"> <layout xsi:type="CSVLayout"> <column name="time" layout="${longdate}" /> <column name="message" layout="${message}" /> <column name="logger" layout="${logger}"/> <column name="level" layout="${level}"/> </layout> </target> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="csv" /> </rules> </nlog>
Size-based file archival
Log files can be automatically archived by moving them to another location after reaching certain size. The following configuration will create logs/logfile.txt which will be archived to archives/log.000000.txt', archives/log.000001.txt', archives/log.000002.txt' and so on once the main log file reaches 10KB.
<?xml version="1.0" ?> <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" layout="${longdate} ${logger} ${message}" fileName="${basedir}/logs/logfile.txt" archiveFileName="${basedir}/archives/log.{#####}.txt" archiveAboveSize="10240" archiveNumbering="Sequence" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
Time-based file archival
Log files can calso be automatically archived based on time. This configuration will archive a file at the beginning of each day and will use rolling file naming, so log file from the previous day can always be found in archives//log.0.txt, log from two days ago is in archives//log.1.txt and so on. This configuration will keep at most 7 archive files, so logs older than one week will be automatically deleted.
<?xml version="1.0" ?> <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" layout="${longdate} ${logger} ${message}" fileName="${basedir}/logs/logfile.txt" archiveFileName="${basedir}/archives/log.{#}.txt" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="7" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>




