Last updated: 2006-09-18

This website is based on NLog v1.0. Click here to view the documentation for other versions.

File Target


Writes logging messages to one or more files.

AssemblyClass.NET Framework.NET CFMono on WindowsMono on Unix
1.01.12.01.02.01.02.01.02.0
NLog.dllNLog.Targets.FileTarget

Parameters (blue fields are required):

NameTypeDescription
fileNamestring  ${}
The name of the file to write to.

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.

Example

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
All Debug messages will go to Debug.log, all Info messages will go to Info.log and so on. You can combine as many of the layout renderers as you want to produce an arbitrary log file name.

layoutstring  ${}
The text to be rendered.

Default value is: ${longdate}|${level:uppercase=true}|${logger}|${message}.

namestring
The name of the target.
archiveAboveSizeInt64
Automatically archive log files that exceed the specified size in bytes.

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 setting ConcurrentWrites to false for maximum performance.

archiveEveryArchiveEveryMode
Automatically archive log files every time the specified time passes. Possible options are: year, month, day, hour, minute. Files are moved to the archive as part of the write operation if the current period of time changes. For example if the current hour changes from 10 to 11, the first write that will occur on or after 11:00 will trigger the archiving.

Possible values are:

  • None - Don't archive based on time.
  • Year - Archive every year.
  • Month - Archive every month.
  • Day - Archive daily.
  • Hour - Archive every hour.
  • Minute - Archive every minute.

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 setting ConcurrentWrites to false for maximum performance.

archiveFileNamestring  ${}
The name of the file to be used for an archive. It 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.
archiveNumberingArchiveNumberingMode
Determines the way file archives are numbered.

Possible values are:

  • Sequence - Sequence style numbering. The most recent archive has the highest number.
  • Rolling - Rolling style numbering (the most recent is always #0 then #1, ..., #N

autoFlushboolean
Automatically flush the file buffers after each log message.

Default value is: True.

bufferSizeinteger
Log file buffer size in bytes.

Default value is: 32768.

concurrentWriteAttemptDelayinteger
The delay in milliseconds to wait before attempting to write to the file again.

Default value is: 1.

The 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.

Example

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.

concurrentWriteAttemptsinteger
The number of times the write is appended on the file before NLog discards the log message.

Default value is: 10.

concurrentWritesboolean
Enables concurrent writes to the log file by multiple processes on the same host.

Default value is: True.

This makes multi-process logging possible. NLog uses a special technique that lets it keep the files open for writing.

createDirsboolean
Create directories if they don't exist.

Default value is: True.

Setting 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.

deleteOldFileOnStartupboolean
Delete old log file on startup.

Default value is: False.

This option works only when the "fileName" parameter denotes a single file.

enableFileDeleteboolean
Enable log file(s) to be deleted.

Default value is: True.

encodingstring
File encoding.

Can be any encoding name supported by System.Text.Encoding.GetEncoding() e.g. windows-1252, iso-8859-2.

fileAttributesWin32FileAttributes
File attributes (Windows only).

Possible values are:

  • Readonly - Read-only
  • Hidden - Hidden
  • System - System
  • Archive - File should be archived.
  • Device - Device
  • Normal - Normal
  • Temporary - File is temporary (should be kept in cache and not written to disk if possible)
  • SparseFile - Sparse file.
  • ReparsePoint - Reparse point.
  • Compressed - Compress file contents.
  • NotContentIndexed - File should not be indexed by the content indexing service.
  • Encrypted - Encrypt file.
  • WriteThrough - The system writes through any intermediate cache and goes directly to disk.
  • NoBuffering - The system opens a file with no system caching
  • DeleteOnClose - Delete file after it is closed.
  • PosixSemantics - A file is accessed according to POSIX rules.

footerstring  ${}
Footer
headerstring  ${}
Header
keepFileOpenboolean
Keep log file open instead of opening and closing it on each logging event.

Default value is: False.

Setting this property to True helps improve performance.

lineEndingLineEndingMode
Line ending mode.

Possible values are:

  • Default - Insert platform-dependent end-of-line sequence after each line.
  • CRLF - Insert CR LF sequence (ASCII 13, ASCII 10) after each line.
  • CR - Insert CR character (ASCII 13) after each line.
  • LF - Insert LF character (ASCII 10) after each line.
  • None - Don't insert any line ending.

maxArchiveFilesinteger
Maximum number of archive files that should be kept.

Default value is: 9.

networkWritesboolean
Disables open-fi

Default value is: False.

openFileCacheSizeinteger
The 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).

Default value is: 5.

The 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.

openFileCacheTimeoutinteger
Maximum number of seconds that files are kept open. If this number is negative.

Default value is: -1.

replaceFileContentsOnEachWriteboolean
Replace file contents on each write instead of appending log message at the end.

Default value is: False.

Example:

To set up the target in the configuration file, use the following syntax:

<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> 

You can use a single target to write to multiple files. The following example writes each log message to a file named after its log level, so it will create: Trace.log, Debug.log, Info.log, Warn.log, Error.log, Fatal.log

<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> 

The file names can be quite complex for the most demanding scenarios. This example shows a way to create separate files for each day, user and log level. As you can see, the possibilities are endless.

<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}/${windows-identity:domain=false}.${level}.log"/> 
  </targets> 
  <rules> 
    <logger name="*" minlevel="Debug" writeTo="file"/> 
  </rules> 
</nlog> 

Depending on your usage scenario it may be useful to add an asynchronous target wrapper around the file target. This way all your log messages will be written in a separate thread so your main thread can finish your work 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.

<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> 

The above examples assume just one target and a single rule. See below for a programmatic configuration that's equivalent to the above config file:

using NLog; 
using NLog.Targets; 
using NLog.Targets.Wrappers; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.txt"; 
        target.KeepFileOpen = false; 
        target.Encoding = "iso-8859-2"; 
 
        AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); 
        wrapper.WrappedTarget = target; 
        wrapper.QueueLimit = 5000; 
        wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
        logger.Debug("log message"); 
    } 
}

More configuration options are described here.

To set up the log target programmatically use code like this:

using NLog; 
using NLog.Targets; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.txt"; 
        target.KeepFileOpen = false; 
        target.Encoding = "iso-8859-2"; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
        logger.Debug("log message"); 
    } 
}

File target can also do file archiving, meaning that the log file is automatically moved to another place based on its size and time. This example demonstrates file archiving based on size. Files after 10000 bytes are moved to a separate folder and renamed log.00000.txt, log.00001.txt and so on.

using NLog; 
using NLog.Targets; 
using NLog.Targets.Wrappers; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.txt"; 
        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt"; 
        target.ArchiveAboveSize = 10 * 1024; // archive files greater than 10 KB 
        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Sequence; 
 
        // this speeds up things when no other processes are writing to the file 
        target.ConcurrentWrites = true; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
         
        // generate a large volume of messages 
        for (int i = 0; i < 1000; ++i) 
        { 
            logger.Debug("log message {0}", i); 
        } 
    } 
}

File archiving can also be done on date/time changes. For example, to create a new archive file every minute use this code:

using NLog; 
using NLog.Targets; 
using NLog.Targets.Wrappers; 
using System.Threading; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.txt"; 
        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt"; 
        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute; 
        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling; 
        target.MaxArchiveFiles = 3; 
 
        // this speeds up things when no other processes are writing to the file 
        target.ConcurrentWrites = true; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
 
        // generate a large number of messages, sleeping 1 second between writes 
        // to observe time-based archiving which occurs every minute 
 
        // 
        // you get: 
        //      logs/logfile.txt 
        // 
        // and your archives go to: 
        // 
        //      archives/log.00000.txt 
        //      archives/log.00001.txt 
        //      archives/log.00002.txt 
        //      archives/log.00003.txt 
        //      archives/log.00004.txt 
 
        for (int i = 0; i < 250; ++i) 
        { 
            logger.Debug("log message {i}", i); 
            Thread.Sleep(1000); 
        } 
    } 
}

You can combine both methods as demonstrated here:

using NLog; 
using NLog.Targets; 
using NLog.Targets.Wrappers; 
using System.Threading; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.txt"// where to store the archive files 
        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt"; 
        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute; 
        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling; 
        target.MaxArchiveFiles = 3; 
        target.ArchiveAboveSize = 10000; 
 
        // this speeds up things when no other processes are writing to the file 
        target.ConcurrentWrites = true; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
 
        // generate a large number of messages, sleeping 1/10 of second between writes 
        // to observe time-based archiving which occurs every minute 
        // the volume is high enough to cause ArchiveAboveSize to be triggered 
        // so that log files larger than 10000 bytes are archived as well 
 
        // 
        // you get: 
        //      logs/logfile.txt 
        // 
        // and your archives go to: 
        // 
        //      archives/log.00000.txt 
        //      archives/log.00001.txt 
        //      archives/log.00002.txt 
        //      archives/log.00003.txt 
        //      archives/log.00004.txt 
 
        for (int i = 0; i < 2500; ++i) 
        { 
            logger.Debug("log message {i}", i); 
            Thread.Sleep(100); 
        } 
    } 
}

Note that file archiving works even when you use a single target instance to write to multiple files, such as putting each log level in a separate place:

using NLog; 
using NLog.Targets; 
using NLog.Targets.Wrappers; 
using System.Threading; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.Layout = "${longdate} ${logger} ${message}"; 
        target.FileName = "${basedir}/logs/logfile.${level}.txt"// where to store the archive files 
        target.ArchiveFileName = "${basedir}/archives/${level}/log.{#####}.txt"; 
        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute; 
        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling; 
        target.MaxArchiveFiles = 3; 
        target.ArchiveAboveSize = 10000; 
 
        // this speeds up things when no other processes are writing to the file 
        target.ConcurrentWrites = true; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
 
        // generate a large number of messages, sleeping 1/10 of second between writes 
        // to observe time-based archiving which occurs every minute 
        // the volume is high enough to cause ArchiveAboveSize to be triggered 
        // so that log files larger than 10000 bytes are archived as well 
 
        // in this version, a single File target keeps track of 3 sets of log and  
        // archive files, one for each level 
 
        // you get: 
        //      logs/logfile.Debug.txt 
        //      logs/logfile.Error.txt 
        //      logs/logfile.Fatal.txt 
        // 
        // and your archives go to: 
        // 
        //      archives/Debug/log.00000.txt 
        //      archives/Debug/log.00001.txt 
        //      archives/Debug/log.00002.txt 
        //      archives/Debug/log.00003.txt 
        //      archives/Error/log.00000.txt 
        //      archives/Error/log.00001.txt 
        //      archives/Error/log.00002.txt 
        //      archives/Error/log.00003.txt 
        //      archives/Fatal/log.00000.txt 
        //      archives/Fatal/log.00001.txt 
        //      archives/Fatal/log.00002.txt 
        //      archives/Fatal/log.00003.txt 
 
        for (int i = 0; i < 2500; ++i) 
        { 
            logger.Debug("log message {i}", i); 
            logger.Error("log message {i}", i); 
            logger.Fatal("log message {i}", i); 
            Thread.Sleep(100); 
        } 
    } 
}

You can write texts using alternative layouts, such as CSV (comma-separated values). This example writes files which are properly CSV-quoted (can handle messages with line breaks and quotes)

using System; 
 
using NLog; 
using NLog.Targets; 
using NLog.Layouts; 
 
class Example 
{ 
    static void Main(string[] args) 
    { 
        FileTarget target = new FileTarget(); 
        target.FileName = "${basedir}/file.csv"; 
 
        CsvLayout layout = new CsvLayout(); 
 
        layout.Columns.Add(new CsvColumn("time", "${longdate}")); 
        layout.Columns.Add(new CsvColumn("message", "${message}")); 
        layout.Columns.Add(new CsvColumn("logger", "${logger}")); 
        layout.Columns.Add(new CsvColumn("level", "${level}")); 
 
        target.CompiledLayout = layout; 
 
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); 
 
        Logger logger = LogManager.GetLogger("Example"); 
        logger.Debug("log message"); 
        logger.Debug("Message with \"quotes\" and \nnew line characters."); 
    } 
}
This is the configuration file version:
<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> 

Back to the target list.
Webwww.nlog-project.org