Writes log messages to one or more files.

Since NLog 4.3 the ${basedir} isn't needed anymore for relative paths.

Supported in .NET, Silverlight, Compact Framework and Mono.

Configuration Syntax

  1. <targets>
  2. <target xsi:type="File"
  3. name="String"
  4. layout="Layout"
  5. header="Layout"
  6. footer="Layout"
  7. encoding="Encoding"
  8. lineEnding="Enum"
  9. archiveAboveSize="Long"
  10. maxArchiveFiles="Integer"
  11. archiveFileName="Layout"
  12. archiveNumbering="Enum"
  13. archiveEvery="Enum"
  14. replaceFileContentsOnEachWrite="Boolean"
  15. fileAttributes="Enum"
  16. fileName="Layout"
  17. deleteOldFileOnStartup="Boolean"
  18. enableFileDelete="Boolean"
  19. createDirs="Boolean"
  20. concurrentWrites="Boolean"
  21. openFileCacheTimeout="Integer"
  22. openFileCacheSize="Integer"
  23. networkWrites="Boolean"
  24. concurrentWriteAttemptDelay="Integer"
  25. concurrentWriteAttempts="Integer"
  26. bufferSize="Integer"
  27. autoFlush="Boolean"
  28. keepFileOpen="Boolean"
  29. forceManaged="Boolean"
  30. enableArchiveFileCompression="Boolean"
  31. cleanupFileName="Boolean" />
  32. </targets>

Read more about using the Configuration File.

Parameters

General Options

name - Name of the target.

forceManaged - Indicates that the file target should only use managed methods. This disables some of the options.

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 name like "utf-8", "ascii" or "utf-16". See Encoding class on MSDN. Defaults to Encoding.Default (UTF-8 on silverlight)

lineEnding - Line ending mode. Possible values:

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

Archival Options

archiveAboveSize - Size in bytes above which log files will be automatically archived. Long 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. *Warning: combining this mode with Archive Numbering Date is not supported. Archive files are not merged. _ DateAndSequence_ do will work. *

maxArchiveFiles - Maximum number of archive files that should be kept. Integer Default: 9

archiveFileName - Name of the file to be used for an archive. Layout 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.

archiveNumbering - Way file archives are numbered. Possible values:

  • Rolling - Rolling style numbering (the most recent is always #0 then #1, ..., #N).
  • Sequence - Sequence style numbering. The most recent archive has the highest number.
  • Date - Date style numbering. The date is formatted according to the value of archiveDateFormat. *Warning: combining this mode with archiveAboveSize is not supported. Archive files are not merged. *
  • DateAndSequence - Combination of Date and Sequence .Archives will be stamped with the prior period (Year, Month, Day) datetime. The most recent archive has the highest number (in combination with the date). The date is formatted according to the value of archiveDateFormat.

See Archive Numbering Examples

archiveEvery - Indicates whether to automatically archive log files every time the specified time passes. Possible values:

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

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

archiveDateFormat - Specifies the date format used for archive numbering. Default format depends on the archive period.

This option works only when the "ArchiveNumbering" parameter is set to Date

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:

  • Archive - File should be archived.
  • Compressed - Compress won't work due to .Net restrictions. You can use enableArchiveFileCompression.
  • DeleteOnClose - Delete file after it is closed.
  • Device - Device file.
  • Encrypted - Encrypted file.
  • Hidden - Hidden file.
  • NoBuffering - The system opens a file with no system caching.
  • Normal - Normal file.
  • NotContentIndexed - File should not be indexed by the content indexing service.
  • PosixSemantics - A file is accessed according to POSIX rules.
  • Readonly - Read-only
  • ReadOnly - Read-only file.
  • ReparsePoint - Reparse point.
  • SparseFile - Sparse file.
  • System - System file.
  • Temporary - File is temporary (should be kept in cache and not written to disk if possible).
  • WriteThrough - The system writes through any intermediate cache and goes directly to disk. > This parameter is not supported in: > * 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 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. Since NLog 4.3 the ${basedir} isn't needed anymore for relative paths.

deleteOldFileOnStartup - Indicates whether to delete old log file on startup. Boolean Default: False This 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: 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.

enableArchiveFileCompression - Indicates whether to compress the archive files into the zip files.Boolean Default: False > Supported in: > * NLog v4.0 for .NET 4.5

Performance Tuning Options

concurrentWrites - Indicates whether concurrent writes to the log file by multiple processes on the same host. Boolean Default: True This makes multi-process logging possible. NLog uses a special technique that lets it keep the files open for writing. NOTE: are ignored unless keepFileOpen are set to true.

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

networkWrites - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. Boolean Default: False This effectively prevents files from being kept open.

concurrentWriteAttemptDelay - Delay in milliseconds to wait before attempting to write to the file again. Integer Default: 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. 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

cleanupFileName - before writing to a file, the name of the file get checked for illegal characters (OS dependent). This can be costly if a lot of messages are written. The cleanup is cached for fixed names (no layout renderers). Set this to false for optimal performance (but beware of the file name, if it's wrong, nothing gets written). Default: true. Introduced in NLog 4.2.3.

bufferSize - Log file buffer size in bytes. Integer Default: 32768

autoFlush - Indicates whether to automatically flush the file buffers after each log message. BooleanDefault: True

keepFileOpen - Indicates whether to keep log file open instead of opening and closing it on each logging event. Boolean Default: False Setting 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.

  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>

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

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
  • ...
  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}.log" />
  9. </targets>
  10.  
  11. <rules>
  12. <logger name="*" minlevel="Debug" writeTo="file" />
  13. </rules>
  14. </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.

  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>

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:

  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>

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.

  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. archiveFileName="${basedir}/archives/log.{#####}.txt"
  10. archiveAboveSize="10240"
  11. archiveNumbering="Sequence"
  12. concurrentWrites="true"
  13. keepFileOpen="false"
  14. encoding="iso-8859-2" />
  15. </targets>
  16.  
  17. <rules>
  18. <logger name="*" minlevel="Debug" writeTo="file" />
  19. </rules>
  20. </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.

  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. archiveFileName="${basedir}/archives/log.{#}.txt"
  10. archiveEvery="Day"
  11. archiveNumbering="Rolling"
  12. maxArchiveFiles="7"
  13. concurrentWrites="true"
  14. keepFileOpen="false"
  15. encoding="iso-8859-2" />
  16. </targets>
  17.  
  18. <rules>
  19. <logger name="*" minlevel="Debug" writeTo="file" />
  20. </rules>
  21. </nlog>

Archive Numbering Examples

Rolling

  1. <target name="file" xsi:type="File"
  2. ...
  3. archiveFileName="log.{####}.txt"
  4. archiveNumbering="Rolling" />

Example archive file names:

  • log.0000.txt
  • log.0001.txt
  • log.0002.txt

Sequence

  1. <target name="file" xsi:type="File"
  2. ...
  3. archiveFileName="log.{####}.txt"
  4. archiveNumbering="Sequence" />

Example archive file names:

  • log.0000.txt
  • log.0001.txt
  • log.0002.txt

Date

  1. <target name="file" xsi:type="File"
  2. ...
  3. archiveFileName="log.{#}.txt"
  4. archiveNumbering="Date"
  5. archiveEvery="Day"
  6. archiveDateFormat="yyyyMMdd"
  7. />

Example archive file names:

  • log.20150730.txt
  • log.20150731.txt

DateAndSequence

  1. <target name="file" xsi:type="File"
  2. ...
  3. archiveFileName="log.{#}.txt"
  4. archiveNumbering="DateAndSequence"
  5. archiveAboveSize="1000"
  6. archiveDateFormat="yyyyMMdd"
  7. />

Example archive file names:

  • log.20150730.1.txt
  • log.20150730.2.txt
  • log.20150730.3.txt

Nlog 配置总结的更多相关文章

  1. ASP.NET Core根据环境切换NLog配置

    1.新建NLog配置文件,名称分别为nlog.config和nlog.debug.config <?xml version="1.0"?> <nlog xmlns ...

  2. Nlog配置

    初次使用nlog,里里外外找了好久,终于搞会了. 使用nlog建日志输出到txt文件.数据库.邮件 nlog配置,如图 码云dome

  3. NLog 配置

    之前我介绍过如何使用log4net来记录日志,但最近喜欢上了另一个简单好用的日志框架NLog. 关于NLog和log4net的比较这里就不多讨论了,感兴趣的朋友可以参看.NET日志工具介绍和log4n ...

  4. NLog 配置与使用

    有段时间没写博客了,过年放假,一直在弄CMS.什么都自己写了一遍,今天写写NLog,之前一用的log4net,感觉配置起来还是有些麻烦. NuGet 添加组件 配置 NLog.config <? ...

  5. Nlog配置实例

      彩色Console target <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns= ...

  6. NLog配置分享

    新建一个文件命名为NLog.Config,然后添加如下代码 <?xml version="1.0" encoding="utf-8" ?> < ...

  7. NLog配置JsonLayout中文输出为unicode问题

    日志输出现要改为json格式,网上查询layout配置为JsonLayout就可以了,结果发现输出中文为unicode编码,看很多文章说配置encode="false"就可以了,结 ...

  8. 常用NLog配置

    <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSe ...

  9. .net core webapi +ddd(领域驱动)+nlog配置+swagger配置 学习笔记(1)

    搭建一个.net core webapi项目  在开始之前,请先安装最新版本的VS2017,以及最新的.net core 2.1. 首先创建一个Asp.Net Core Web应用程序 这个应用程序是 ...

随机推荐

  1. 英特尔® 硬件加速执行管理器安装指南 — Microsoft Windows*

    介绍 本文将指导您安装英特尔® 硬件加速执行管理器(英特尔® HAXM),这是一款可以使用英特尔® 虚拟化技术(VT)加快 Android* 开发速度的硬件辅助虚拟化引擎(管理程序). 前提条件 英特 ...

  2. 【Linux探索之旅】第一部分第五课:Unity桌面,人生若只如初见

    内容简介 1.第一部分第五课:Unity桌面,人生若只如初见 2.第一部分第六课预告:Linux如何安装在虚拟机中 Unity桌面,人生若只如初见 不容易啊,经过了前几课的学习,我们认识了Linux是 ...

  3. CSS设计指南之浮动与清除

    原文:CSS设计指南之浮动与清除 浮动意思就是把元素从常规文档流中拿出来,浮动元素脱离了常规文档流之后,原来紧跟在其后的元素就会在空间允许的情况下,向上提升到与浮动元素平起平坐. 一.浮动 CSS设计 ...

  4. HDU 1874 畅通公程续 (最短路 水)

    Problem Description 某省自从实行了非常多年的畅通project计划后,最终修建了非常多路.只是路多了也不好,每次要从一个城镇到还有一个城镇时,都有很多种道路方案能够选择,而某些方案 ...

  5. 2015-12-1 Visual Studio 2015 Update 1发布

    http://news.cnblogs.com/n/533856/ 下载地址 文件名 cn_visual_studio_enterprise_2015_with_update_1_x86_x64_dv ...

  6. chrome(转)

    阅读目录 Chrome的隐身模式 Chrome下各种组合键 Chrome的about指令 chrome://accessibility     查看浏览器当前访问的标签 chrome://appcac ...

  7. uml学习书籍

     uml真正实用的书5这是足够.学习如以下的处理: <UML distilled><--><UML和模式应用>-><UML用户指南> 附加两本&l ...

  8. Visual Studio中开发

    如何在Visual Studio中开发自己的代码生成器插件    Visual Studio是美国微软公司开发的一个基本完整的开发工具集,它包括了整个软件生命周期中所需要的大部分工具,如UML工具.代 ...

  9. 【Espruino】NO.03 从点灯开始

    http://blog.csdn.net/qwert1213131/article/details/26819773 本文属于个人理解,能力有限,纰漏在所难免,还望指正! [小鱼有点电] 点灯程序应该 ...

  10. Jeditable 点击编辑文字插件

    Jeditable - jQuery就地编辑插件使用   jeditable是一个jquery插件,它的优点是可以就地编辑,并且提交到服务器处理,是一个不可多得的就地编辑插件.(注: 就地编辑,也有称 ...