A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/NLog/NLog/wiki/File-target below:

File target · NLog/NLog Wiki · GitHub

Writes log messages to one or more files.

Platforms Supported: All

<targets>
  <target xsi:type="File"
          name="String"
          layout="Layout"
          header="Layout"
          footer="Layout"
          encoding="Encoding"
          lineEnding="Enum"
          archiveAboveSize="Long"
          maxArchiveFiles="Integer"
          maxArchiveDays="Integer"
          archiveFileName="Layout"
          archiveEvery="Enum"
          archiveOldFileOnStartup="Boolean"
          replaceFileContentsOnEachWrite="Boolean"
          fileName="Layout"
          deleteOldFileOnStartup="Boolean"
          enableFileDelete="Boolean"
          createDirs="Boolean"
          openFileFlushTimeout="Integer"
          openFileCacheTimeout="Integer"
          openFileCacheSize="Integer"
          bufferSize="Integer"
          autoFlush="Boolean"
          keepFileOpen="Boolean"
          writeFooterOnArchivingOnly="Boolean"
          writeHeaderWhenInitialFileNotEmpty="Boolean"
          writeBom="Boolean" />
</targets>

Read more about using the Configuration File.

Performance Tuning Options

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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd">
 
    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
            fileName="${basedir}/logs/logfile.txt" 
            keepFileOpen="true"
            encoding="utf-8" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

File Target supports relative paths since NLog 4.3, where it will implicitly use ${BaseDir} (AppDomain.BaseDirectory). It is also possible to specify an absolute path or make use of these helpers:

Example using CommonApplicationData which is good when running as Windows Service:

To remove all doubt, then one can also use absolute-paths. And by using NLog config variables then one can reuse the absolute path for multiple file targets:

<variable name="logDirectory" value="C:/AppDir/" />
<targets>
<target type="file" name="logfile" filename="${logDirectory}App.log" />
</targets>

It is also possible to override the directory at runtime using GDC:

<targets>
<target type="file" name="logfile" filename="${gdc:logDirectory:whenEmpty=${baseDir}}/App.log" />
</targets>
NLog.GlobalDiagnosticsContext.Set("logDirectory", "C:/Temp/");
Batch write and asynchronous logging

The file target has support for batch writing, where multiple log messages are written in one file-operation. Batch write will improve performance, especially when using KeepFileOpen=false. Batch writing is enabled automatically when using the AsyncWrapper. This can be done by adding the attribute async="true" to the <targets>-element.

Asynchronous logging is recommended for multi-threaded server applications, but might not be worth it for quick-finishing command line application. Make sure to remember to flush at application shutdown, or else output can be dropped.

<?xml version="1.0" ?>
<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">
 
    <targets async="true">
        <target type="File" name="logfile" fileName="${basedir}/logs/${level}.txt" keepFileOpen="true" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>
Multi processes writing same file

The IIS-application can run multiple AppDomains, and each AppDomain operates like a child process. When multiple processes are concurrently writing to the same file, then some locking for coordination is needed:

NLog v6 has removed support for ConcurrentWrites-option in the standard NLog File-Target. Instead one must use additional nuget-package like Atomic-File-Target or NLog.Targets.ConcurrentFile.

It is recommended to enable asynchronous logging as it will reduce the overhead from file locking coordination (Especially when using KeepFileOpen=false and ConcurrentWrites=true).

NLog 4.5 makes it easy to setup archive logic to cleanup old files when using dynamic fileName-Layout. You just need to configure maxArchiveFiles and it will automatically perform cleanup.

<?xml version="1.0" ?>
<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">
 
    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
            fileName="${basedir}/logs/AppLog.${shortdate}.txt" 
            maxArchiveFiles="4"
            archiveAboveSize="10240" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

NLog 4.7 (and newer) adds support for the option MaxArchiveDays. It works like MaxArchiveFiles but instead inspect the timestamp of the files in the archive. They can be combined. Ex. maxArchiveDays="30" maxArchiveFiles="90" (Deletes files older than 30 days or if more than 90 files in archive).

Dynamic vs. Static Archive Logic

Do not mix "Dynamic FileName Archive Logic" together with "Static FileName Archive Logic" as one will get unexpected archive behavior.

Static-filename-archive-logic are well suited for being used with tail-applications, that monitors a single static-filename. But there might be issues when NLog tries to rename/move the old file to create new file (Ex. when locked by external file-viewer). It is possible to move files into a different folder when using static-filename-archive-logic:

There are several FileTarget-Archive-Examples of how to use Static FileName with ArchiveEvery.

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:

<?xml version="1.0" ?>
<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">
 
    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}${exception:format=ToString}" 
            fileName="${basedir}/${level}.log" />
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

The NLog FileTarget can be combined with the JsonLayout to create Json-LogFile:

<?xml version="1.0" ?>
<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">
    <targets>
        <target name="jsonfile" xsi:type="File" fileName="${basedir}/file.json">
            <layout xsi:type="JsonLayout">
                <attribute name="time" layout="${date:format=O}" />
                <attribute name="message" layout="${message}" />
                <attribute name="logger" layout="${logger}"/>
                <attribute name="level" layout="${level}"/>
            </layout>
        </target>
    </targets>
 
    <rules>
        <logger name="*" minlevel="Debug" writeTo="jsonfile" />
    </rules>
</nlog>

The NLog FileTarget can be combined with the CsvLayout to create comma-separated CSV-LogFile. Here is an example of a file with 4 columns:

<?xml version="1.0" ?>
<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">
    <targets>
        <target name="csvfile" 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="csvfile" />
    </rules>
</nlog>

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4