[This is preliminary documentation and is subject to change.]

Writes logging messages to one or more files.

Namespace:  NLog.Targets
Assembly:  NLog (in NLog.dll) Version: 2.0.0.0

Syntax

C#
public class FileTarget : TargetWithLayoutHeaderAndFooter
Visual Basic (Declaration)
Public Class FileTarget _
	Inherits TargetWithLayoutHeaderAndFooter
Visual C++
public ref class FileTarget : public TargetWithLayoutHeaderAndFooter

Examples

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

CopyXML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <target name="file" xsi:type="File"
 7            layout="${longdate} ${logger} ${message}" 
 8            fileName="${basedir}/logs/logfile.txt" 
 9            keepFileOpen="false"
10            encoding="iso-8859-2" />
11    </targets>
12
13    <rules>
14        <logger name="*" minlevel="Debug" writeTo="file" />
15    </rules>
16</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

CopyXML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <target name="file" xsi:type="File"
 7            layout="${longdate} ${logger} ${message}" 
 8            fileName="${basedir}/${level}.log" />
 9    </targets>
10
11    <rules>
12        <logger name="*" minlevel="Debug" writeTo="file" />
13    </rules>
14</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.

CopyXML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <target name="file" xsi:type="File"
 7            layout="${longdate} ${logger} ${message}" 
 8            fileName="${basedir}/${shortdate}/${windows-identity:domain=false}.${level}.log" />
 9    </targets>
10
11    <rules>
12        <logger name="*" minlevel="Debug" writeTo="file" />
13    </rules>
14</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.

CopyXML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <!-- Log in a separate thread, possibly queueing up to
 7        5000 messages. When the queue overflows, discard any
 8        extra messages-->
 9
10        <target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
11            <target xsi:type="File" fileName="${basedir}/logs/${level}.txt" />
12        </target>
13    </targets>
14
15    <rules>
16        <logger name="*" minlevel="Debug" writeTo="file" />
17    </rules>
18</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:

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4using System.Text;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        FileTarget target = new FileTarget();
11        target.Layout = "${longdate} ${logger} ${message}";
12        target.FileName = "${basedir}/logs/logfile.txt";
13        target.KeepFileOpen = false;
14        target.Encoding = Encoding.UTF8;
15
16        AsyncTargetWrapper wrapper = new AsyncTargetWrapper();
17        wrapper.WrappedTarget = target;
18        wrapper.QueueLimit = 5000;
19        wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard;
20
21        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug);
22
23        Logger logger = LogManager.GetLogger("Example");
24        logger.Debug("log message");
25    }
26}

More configuration options are described here.

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

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using System.Text;
 4
 5class Example
 6{
 7    static void Main(string[] args)
 8    {
 9        FileTarget target = new FileTarget();
10        target.Layout = "${longdate} ${logger} ${message}";
11        target.FileName = "${basedir}/logs/logfile.txt";
12        target.KeepFileOpen = false;
13        target.Encoding = Encoding.UTF8;
14
15        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
16
17        Logger logger = LogManager.GetLogger("Example");
18        logger.Debug("log message");
19    }
20}

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.

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4
 5class Example
 6{
 7    static void Main(string[] args)
 8    {
 9        FileTarget target = new FileTarget();
10        target.Layout = "${longdate} ${logger} ${message}";
11        target.FileName = "${basedir}/logs/logfile.txt";
12        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt";
13        target.ArchiveAboveSize = 10 * 1024; // archive files greater than 10 KB
14        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Sequence;
15
16        // this speeds up things when no other processes are writing to the file
17        target.ConcurrentWrites = true;
18
19        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
20
21        Logger logger = LogManager.GetLogger("Example");
22
23        // generate a large volume of messages
24        for (int i = 0; i < 1000; ++i)
25        {
26            logger.Debug("log message {0}", i);
27        }
28    }
29}

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

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4using System.Threading;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        FileTarget target = new FileTarget();
11        target.Layout = "${longdate} ${logger} ${message}";
12        target.FileName = "${basedir}/logs/logfile.txt";
13        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt";
14        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute;
15        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling;
16        target.MaxArchiveFiles = 3;
17
18        // this speeds up things when no other processes are writing to the file
19        target.ConcurrentWrites = true;
20
21        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
22
23        Logger logger = LogManager.GetLogger("Example");
24
25        // generate a large number of messages, sleeping 1 second between writes
26        // to observe time-based archiving which occurs every minute
27
28        // 
29        // you get:
30        //      logs/logfile.txt
31        // 
32        // and your archives go to:
33        // 
34        //      archives/log.00000.txt
35        //      archives/log.00001.txt
36        //      archives/log.00002.txt
37        //      archives/log.00003.txt
38        //      archives/log.00004.txt
39
40        for (int i = 0; i < 250; ++i)
41        {
42            logger.Debug("log message {i}", i);
43            Thread.Sleep(1000);
44        }
45    }
46}

You can combine both methods as demonstrated here:

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4using System.Threading;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        FileTarget target = new FileTarget();
11        target.Layout = "${longdate} ${logger} ${message}";
12        target.FileName = "${basedir}/logs/logfile.txt";
13        // where to store the archive files
14        target.ArchiveFileName = "${basedir}/archives/log.{#####}.txt";
15        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute;
16        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling;
17        target.MaxArchiveFiles = 3;
18        target.ArchiveAboveSize = 10000;
19
20        // this speeds up things when no other processes are writing to the file
21        target.ConcurrentWrites = true;
22
23        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
24
25        Logger logger = LogManager.GetLogger("Example");
26
27        // generate a large number of messages, sleeping 1/10 of second between writes
28        // to observe time-based archiving which occurs every minute
29        // the volume is high enough to cause ArchiveAboveSize to be triggered
30        // so that log files larger than 10000 bytes are archived as well
31
32        // 
33        // you get:
34        //      logs/logfile.txt
35        // 
36        // and your archives go to:
37        // 
38        //      archives/log.00000.txt
39        //      archives/log.00001.txt
40        //      archives/log.00002.txt
41        //      archives/log.00003.txt
42        //      archives/log.00004.txt
43
44        for (int i = 0; i < 2500; ++i)
45        {
46            logger.Debug("log message {i}", i);
47            Thread.Sleep(100);
48        }
49    }
50}

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:

CopyC#
 1using NLog;
 2using NLog.Targets;
 3using NLog.Targets.Wrappers;
 4using System.Threading;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        FileTarget target = new FileTarget();
11        target.Layout = "${longdate} ${logger} ${message}";
12        target.FileName = "${basedir}/logs/logfile.${level}.txt";
13        // where to store the archive files
14        target.ArchiveFileName = "${basedir}/archives/${level}/log.{#####}.txt";
15        target.ArchiveEvery = FileTarget.ArchiveEveryMode.Minute;
16        target.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Rolling;
17        target.MaxArchiveFiles = 3;
18        target.ArchiveAboveSize = 10000;
19
20        // this speeds up things when no other processes are writing to the file
21        target.ConcurrentWrites = true;
22
23        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
24
25        Logger logger = LogManager.GetLogger("Example");
26
27        // generate a large number of messages, sleeping 1/10 of second between writes
28        // to observe time-based archiving which occurs every minute
29        // the volume is high enough to cause ArchiveAboveSize to be triggered
30        // so that log files larger than 10000 bytes are archived as well
31
32        // in this version, a single File target keeps track of 3 sets of log and 
33        // archive files, one for each level
34
35        // you get:
36        //      logs/logfile.Debug.txt
37        //      logs/logfile.Error.txt
38        //      logs/logfile.Fatal.txt
39        // 
40        // and your archives go to:
41        // 
42        //      archives/Debug/log.00000.txt
43        //      archives/Debug/log.00001.txt
44        //      archives/Debug/log.00002.txt
45        //      archives/Debug/log.00003.txt
46        //      archives/Error/log.00000.txt
47        //      archives/Error/log.00001.txt
48        //      archives/Error/log.00002.txt
49        //      archives/Error/log.00003.txt
50        //      archives/Fatal/log.00000.txt
51        //      archives/Fatal/log.00001.txt
52        //      archives/Fatal/log.00002.txt
53        //      archives/Fatal/log.00003.txt
54
55        for (int i = 0; i < 2500; ++i)
56        {
57            logger.Debug("log message {i}", i);
58            logger.Error("log message {i}", i);
59            logger.Fatal("log message {i}", i);
60            Thread.Sleep(100);
61        }
62    }
63}

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)

CopyC#
 1using System;
 2
 3using NLog;
 4using NLog.Targets;
 5using NLog.Layouts;
 6
 7class Example
 8{
 9    static void Main(string[] args)
10    {
11        FileTarget target = new FileTarget();
12        target.FileName = "${basedir}/file.csv";
13
14        CsvLayout layout = new CsvLayout();
15
16        layout.Columns.Add(new CsvColumn("time", "${longdate}"));
17        layout.Columns.Add(new CsvColumn("message", "${message}"));
18        layout.Columns.Add(new CsvColumn("logger", "${logger}"));
19        layout.Columns.Add(new CsvColumn("level", "${level}"));
20
21        target.Layout = layout;
22
23        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
24
25        Logger logger = LogManager.GetLogger("Example");
26        logger.Debug("log message");
27        logger.Debug("Message with \"quotes\" and \nnew line characters.");
28    }
29}

This is the configuration file version:

CopyXML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4    <targets>
 5        <target name="csv" xsi:type="File" fileName="${basedir}/file.csv">
 6            <layout xsi:type="CSVLayout">
 7                <column name="time" layout="${longdate}" />
 8                <column name="message" layout="${message}" />
 9                <column name="logger" layout="${logger}"/>
10                <column name="level" layout="${level}"/>
11            </layout>
12        </target>
13    </targets>
14
15    <rules>
16        <logger name="*" minlevel="Debug" writeTo="csv" />
17    </rules>
18</nlog>

Inheritance Hierarchy

See Also