一、示例代码:
NLog 2.0.1.2
#一、LoggerWrapper
using System;
using System.Text;
using NLog;
namespace LoggerWrapper
{
/// <summary>
/// Provides methods to write messages with event IDs - useful for the Event Log target.
/// Wraps a Logger instance.提供使用事件 ID 编写消息的方法 - 对于事件日志目标很有用。 包装一个 Logger 实例。
/// </summary>
class MyLogger
{
private Logger _logger;
public MyLogger(string name)
{
_logger = LogManager.GetLogger(name);
}
public void WriteMessage(string eventID, string message)
{
///
/// 从传递的消息创建日志事件 create log event from the passed message
///
LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, message);
//
// 设置事件特定的上下文参数set event-specific context parameter
// 此上下文参数可以使用${event-properties:EventID}检索this context parameter can be retrieved using ${event-properties:EventID}
//
logEvent.Properties["EventID"] = eventID;
//
// Call the Log() method. It is important to pass typeof(MyLogger) as the
// first parameter. If you don't, ${callsite} and other callstack-related
// layout renderers will not work properly.
//调用 Log() 方法。 传递 typeof(MyLogger) 作为第一个参数很重要。 如果不这样做,${callsite} 和其他与调用堆栈相关的布局渲染器将无法正常工作。
//
_logger.Log(typeof(MyLogger), logEvent);
}
}
class Program
{
static void Main(string[] args)
{
MyLogger l = new MyLogger("uuu");
l.WriteMessage("1234", "message");
Console.WriteLine("hello");
Console.ReadLine();
}
}
}
#二、InheritFromLogger
using System;
using System.Text;
using NLog;
namespace InheritFromLogger
{
/// <summary>
/// Provides methods to write messages with event IDs - useful for the Event Log target
/// Inherits from the Logger class.提供使用事件 ID 编写消息的方法 - 对于从 Logger 类继承的事件日志目标很有用。
/// </summary>
public class LoggerWithEventID : Logger
{
public LoggerWithEventID()
{
}
//将 eventID 作为参数的附加方法 additional method that takes eventID as an argument
public void DebugWithEventID(int eventID, string message, params object[] args)
{
if (IsDebugEnabled)
{
//创建日志事件 create log event
LogEventInfo lei = new LogEventInfo(LogLevel.Debug, Name, null, message, args);
// 设置每个日志上下文数据set the per-log context data
// 可以使用 ${event-context:EventID} 检索此数据
lei.Context["EventID"] = eventID;
// 记录消息log the message
base.Log(typeof(LoggerWithEventID), lei);
}
}
// other methods omitted for brevity
}
class Program
{
// get the current class logger as an instance of LoggerWithEventID class
//获取当前类记录器作为 LoggerWithEventID 类的实例
private static LoggerWithEventID LoggerWithEventID = (LoggerWithEventID)LogManager.GetCurrentClassLogger(typeof(LoggerWithEventID));
static void Main(string[] args)
{
// this writes 5 messages to the Event Log, each with a different EventID
//这会将 5 条消息写入事件日志,每条消息都有不同的 EventID
LoggerWithEventID.DebugWithEventID(123, "message 1", 1, 2, 3);
LoggerWithEventID.DebugWithEventID(124, "message 2", 1, 2, 3);
LoggerWithEventID.DebugWithEventID(125, "message 3", 1, 2, 3);
LoggerWithEventID.DebugWithEventID(126, "message 4", 1, 2, 3);
LoggerWithEventID.DebugWithEventID(127, "message 5", 1, 2, 3);
}
}
}
#3. AutoFlushWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";
AutoFlushTargetWrapper target = new AutoFlushTargetWrapper();
target.WrappedTarget = wrappedTarget;
target.Condition = "level >= LogLevel.Debug";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#4. AsyncWrapper
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Text;
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 = Encoding.UTF8;//编码格式
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");
wrapper.Flush();
}
}
#5. BufferingWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";//文件名
BufferingTargetWrapper target = new BufferingTargetWrapper();
target.BufferSize = 100;//缓存大小
target.WrappedTarget = wrappedTarget;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#6. Chainsaw 从log4j向Chainsaw应用程序的远程实例发送日志消息
//https://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_ChainsawTarget.htm
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
ChainsawTarget target = new ChainsawTarget();
target.Address = "udp://localhost:4000";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("log message 1");
logger.Debug("log message 2");
logger.Info("log message 3");
logger.Warn("log message 4");
logger.Error("log message 5");
logger.Fatal("log message 6");
}
}
#7. ColoredConsole.Row Highlighting
using NLog;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
ColoredConsoleTarget target = new ColoredConsoleTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.RowHighlightingRules.Add(
new ConsoleRowHighlightingRule(
"level >= LogLevel.Error and contains(message,'serious')", // condition
ConsoleOutputColor.White, // foreground color
ConsoleOutputColor.Red // background color
)
);
target.RowHighlightingRules.Add(
new ConsoleRowHighlightingRule(
"starts-with(logger,'Example')", // condition
ConsoleOutputColor.Yellow, // foreground color
ConsoleOutputColor.DarkBlue) // background color
);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
// LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("ColoredConsoleTargetRowHighlighting.nlog");
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("very serious error log message");
logger.Fatal("fatal log message, rather serious");
Logger logger2 = LogManager.GetLogger("Another");
logger2.Trace("trace log message");
logger2.Debug("debug log message");
logger2.Info("info log message");
logger2.Warn("warn log message");
logger2.Error("very serious error log message");
logger2.Fatal("fatal log message");
}
}
#8. ColoredConsole
using NLog;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
ColoredConsoleTarget target = new ColoredConsoleTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("error log message");
logger.Fatal("fatal log message");
}
}
#9. ColoredConsole.Word Highlighting
using NLog;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
ColoredConsoleTarget target = new ColoredConsoleTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule("log",
ConsoleOutputColor.NoChange,
ConsoleOutputColor.DarkGreen));
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule("abc",
ConsoleOutputColor.Cyan,
ConsoleOutputColor.NoChange));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message abcdefghijklmnopq");
logger.Debug("debug log message");
logger.Info("info log message abc abcdefghijklmnopq");
logger.Warn("warn log message");
logger.Error("error log abcdefghijklmnopq message abc");
logger.Fatal("fatal log message abcdefghijklmnopq abc");
}
}
#10. Console
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
ConsoleTarget target = new ConsoleTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#11. Database.Oracle.OleDb
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
DatabaseTarget target = new DatabaseTarget();
DatabaseParameterInfo param;
target.DBProvider = "oledb";
target.ConnectionString = "Provider=msdaora;Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;";
target.CommandText = "insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values(?,?,?,?,?)";
target.Parameters.Add(new DatabaseParameterInfo("TIME_STAMP", "${longdate}"));
target.Parameters.Add(new DatabaseParameterInfo("LOGLEVEL", "${level:uppercase=true}"));
target.Parameters.Add(new DatabaseParameterInfo("LOGGER", "${logger}"));
target.Parameters.Add(new DatabaseParameterInfo("CALLSITE", "${callsite:filename=true}"));
target.Parameters.Add(new DatabaseParameterInfo("MESSAGE", "${message}"));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#12. Database.Oracle.Native
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
DatabaseTarget target = new DatabaseTarget();
DatabaseParameterInfo param;
target.DBProvider = "System.Data.OracleClient.OracleConnection,System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
target.ConnectionString = "Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;Integrated Security=no;";
target.CommandText = "insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values( :TIME_STAMP,:LOGLEVEL,:LOGGER,:CALLSITE,:MESSAGE)";
target.KeepConnection = true;
target.Parameters.Add(new DatabaseParameterInfo("TIME_STAMP", "${longdate}"));
target.Parameters.Add(new DatabaseParameterInfo("LOGLEVEL", "${level:uppercase=true}"));
target.Parameters.Add(new DatabaseParameterInfo("LOGGER", "${logger}"));
target.Parameters.Add(new DatabaseParameterInfo("CALLSITE", "${callsite:filename=true}"));
target.Parameters.Add(new DatabaseParameterInfo("MESSAGE", "${message}"));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#13. Database.MSSQL
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
DatabaseTarget target = new DatabaseTarget();
DatabaseParameterInfo param;
target.DBProvider = "mssql";
target.DBHost = ".";
target.DBUserName = "nloguser";
target.DBPassword = "pass";
target.DBDatabase = "databasename";
target.CommandText = "insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);";
param = new DatabaseParameterInfo();
param.Name = "@time_stamp";
param.Layout = "${date}";
target.Parameters.Add(param);
param = new DatabaseParameterInfo();
param.Name = "@level";
param.Layout = "${level}";
target.Parameters.Add(param);
param = new DatabaseParameterInfo();
param.Name = "@logger";
param.Layout = "${logger}";
target.Parameters.Add(param);
param = new DatabaseParameterInfo();
param.Name = "@message";
param.Layout = "${message}";
target.Parameters.Add(param);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#14.Debug
using System;
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
DebugTarget target = new DebugTarget();
target.Layout = "${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
logger.Debug("another log message");
Console.WriteLine("The debug target has been hit {0} times.", target.Counter);
Console.WriteLine("The last message was '{0}'.", target.LastMessage);
}
}
#15. Debugger
using System;
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
DebuggerTarget target = new DebuggerTarget();
target.Layout = "${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#16. EventLog
using NLog;
using NLog.Targets;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
EventLogTarget target = new EventLogTarget();
target.Source = "My Source";
target.Log = "Application";
target.MachineName = ".";
target.Layout = "${logger}: ${message}";
target.OnOverflow = EventLogTargetOverflowAction.Truncate;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#17. File
using NLog;
using NLog.Targets;
using System.Text;
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 = Encoding.UTF8;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#18. File.Multiple 日志级别-文件名
using NLog;
using NLog.Targets;
using System.Text;
class Example
{
static void Main(string[] args)
{
FileTarget target = new FileTarget();
target.Layout = "${longdate} ${logger} ${message}";
target.FileName = "${basedir}/${level}.log";
target.KeepFileOpen = false;
target.Encoding = Encoding.UTF8;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#19. File.Multiple2
using NLog;
using NLog.Targets;
using System.Text;
class Example
{
static void Main(string[] args)
{
FileTarget target = new FileTarget();
target.Layout = "${longdate} ${logger} ${message}";
target.FileName = "${basedir}/${shortdate}/${windows-identity:domain=false}.${level}.log";
target.KeepFileOpen = false;
target.Encoding = Encoding.UTF8;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#20. File.CSV
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.Layout = 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.");
}
}
#21. File.Asynchronous 异步日志文件
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Text;
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 = Encoding.UTF8;
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");
}
}
#22. File.Archive1 日志文件达到一定大小归档
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);
}
}
}
#23. File.Archive2 间隔时间归档
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);
}
}
}
#24. File.Archive3
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
//生成大量消息,在写入之间休眠 1/10 秒以观察基于时间的归档,
//该归档每分钟发生一次 卷高到足以触发 ArchiveAboveSize 以便也归档大于 10000 字节的日志文件
//
// 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);
}
}
}
#25. File.Archive4
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";
// 存档文件的存储位置
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
//生成大量消息,在写入之间休眠 1/10 秒以观察基于时间的归档,
//该归档每分钟发生一次 卷高到足以触发 ArchiveAboveSize 以便也归档大于 10000 字节的日志文件
// 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);
}
}
}
#26. FilteringWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";
FilteringTargetWrapper filteringTarget = new FilteringTargetWrapper();
filteringTarget.WrappedTarget = wrappedTarget;
filteringTarget.Condition = "contains('${message}','1')";//过滤条件
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(filteringTarget, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message 0");
logger.Debug("log message 1");
logger.Debug("log message 2");
logger.Debug("log message 11");
}
}
#27. 窗体控件 富文本框 Form1
using System;
using System.Text;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RichTextBox2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormControlTarget target = new FormControlTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = "textBox1";//控件名
target.FormName = "Form1";//窗体名
target.Append = true;//附加
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message, ");
logger.Debug("debug log message, ");
logger.Info("info log message, ");
logger.Warn("warn log message, ");
logger.Error("error log message, ");
logger.Fatal("fatal log message");
}
}
}
#28. Memory
using System;
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
MemoryTarget target = new MemoryTarget();
target.Layout = "${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
foreach (string s in target.Logs)
{
Console.Write("logged: {0}", s);
}
}
}
#29. MessageBox
using System;
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
MessageBoxTarget target = new MessageBoxTarget();
target.Layout = "${longdate}: ${message}";
target.Caption = "${level} message";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#30. MethodCall 方法调用
using System;
using NLog;
using NLog.Targets;
using System.Diagnostics;
public class Example
{
public static void LogMethod(string level, string message)
{
Console.WriteLine("l: {0} m: {1}", level, message);
}
static void Main(string[] args)
{
MethodCallTarget target = new MethodCallTarget();
target.ClassName = typeof(Example).AssemblyQualifiedName;
target.MethodName = "LogMethod";
target.Parameters.Add(new MethodCallParameter("${level}"));
target.Parameters.Add(new MethodCallParameter("${message}"));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
logger.Error("error message");
}
}
#31. MSMQ.Multiple Queues
using NLog;
using NLog.Config;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
NLog.Internal.InternalLogger.LogToConsole = true;
MSMQTarget target = new MSMQTarget();
target.Queue = ".\\private$\\nlog.${level}";
target.Label = "${message}";
target.Layout = "${message}";
target.CreateQueueIfNotExists = true;
target.Recoverable = true;
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger l = LogManager.GetLogger("AAA");
l.Error("This is an error. It goes to .\\private$\\nlog.Error queue.");
l.Debug("This is a debug information. It goes to .\\private$\\nlog.Debug queue.");
l.Info("This is a information. It goes to .\\private$\\nlog.Info queue.");
l.Warn("This is a warn information. It goes to .\\private$\\nlog.Warn queue.");
l.Fatal("This is a fatal information. It goes to .\\private$\\nlog.Fatal queue.");
l.Trace("This is a trace information. It goes to .\\private$\\nlog.Trace queue.");
}
}
#32. Network
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
NetworkTarget target = new NetworkTarget();
target.Layout = "${level} ${logger} ${message}${newline}";
target.Address = "tcp://localhost:5555";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("log message 1");
logger.Debug("log message 2");
logger.Info("log message 3");
logger.Warn("log message 4");
logger.Error("log message 5");
logger.Fatal("log message 6");
}
}
#33.NLogViewer
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
NLogViewerTarget target = new NLogViewerTarget();
target.Address = "udp://localhost:4000";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("log message 1");
logger.Debug("log message 2");
logger.Info("log message 3");
logger.Warn("log message 4");
logger.Error("log message 5");
logger.Fatal("log message 6");
}
}
#34. Null
using System;
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
NullTarget target = new NullTarget();
target.Layout = "${message}";
target.FormatMessage = true;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#35.OutputDebugString
using System;
using NLog;
using NLog.Targets;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
OutputDebugStringTarget target = new OutputDebugStringTarget();
target.Layout = "${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#36. PerfCounter 性能计数器
using System;
using NLog;
using NLog.Targets;
using NLog.Win32.Targets;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
PerfCounterTarget target = new PerfCounterTarget();
target.AutoCreate = true;
target.CategoryName = "My category";
target.CounterName = "My counter";
target.CounterType = PerformanceCounterType.NumberOfItems32;
target.InstanceName = "My instance";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#37. PostFilteringWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";
PostFilteringTargetWrapper postFilteringTarget = new PostFilteringTargetWrapper();
postFilteringTarget.WrappedTarget = wrappedTarget;
// 设置默认过滤器
postFilteringTarget.DefaultFilter = "level >= LogLevel.Info";
FilteringRule rule;
// if there are any warnings in the buffer
// dump the messages whose level is Debug or higher
//如果缓冲区中有任何警告
// 转储 Debug 或更高级别的消息
rule = new FilteringRule();
rule.Exists = "level >= LogLevel.Warn";
rule.Filter = "level >= LogLevel.Debug";
postFilteringTarget.Rules.Add(rule);
BufferingTargetWrapper target = new BufferingTargetWrapper();
target.BufferSize = 100;
target.WrappedTarget = postFilteringTarget;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#38. RandomizeGroup 随机分组
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Compound;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget file1 = new FileTarget();
file1.FileName = "${basedir}/file1.txt";
FileTarget file2 = new FileTarget();
file2.FileName = "${basedir}/file2.txt";
RandomizeTarget target = new RandomizeTarget();
target.Targets.Add(file1);
target.Targets.Add(file2);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#39. RepeatingWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";
RepeatingTargetWrapper target = new RepeatingTargetWrapper();
target.WrappedTarget = wrappedTarget;
target.RepeatCount = 3;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#40. RetryingWrapper
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget wrappedTarget = new FileTarget();
wrappedTarget.FileName = "${basedir}/file.txt";
RetryingTargetWrapper target = new RetryingTargetWrapper();
target.WrappedTarget = wrappedTarget;
target.RetryCount = 3;
target.RetryDelayMilliseconds = 1000;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#41. RichTextBox.RowColoring
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RichTextBox2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RichTextBoxTarget target = new RichTextBoxTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = "richTextBox1";
target.FormName = "Form1";
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
new RichTextBoxRowColoringRule(
"level >= LogLevel.Error and contains(message,'serious')", // condition
"White", // font color
"Red", // background color
FontStyle.Bold | FontStyle.Italic
)
);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("error log message");
logger.Fatal("fatal log message");
logger.Fatal("fatal log message, rather serious");
}
}
}
#42. RichTextBox
using System;
using System.Text;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RichTextBox2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RichTextBoxTarget target = new RichTextBoxTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = "richTextBox1";
target.FormName = "Form1";
target.UseDefaultRowColoringRules = true;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("error log message");
logger.Fatal("fatal log message");
}
}
}
#43. RichTextBox.WordColoring 关键词高亮
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RichTextBox2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RichTextBoxTarget target = new RichTextBoxTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = "richTextBox1";
target.FormName = "Form1";
target.UseDefaultRowColoringRules = false;
target.WordColoringRules.Add(
new RichTextBoxWordColoringRule(
"log", // word
"White", // font color
"Red", // background color
FontStyle.Bold | FontStyle.Italic
)
);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("error log message");
logger.Fatal("fatal log message");
logger.Fatal("fatal log message, rather serious");
}
}
}
#44. RoundRobinGroup
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Compound;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget file1 = new FileTarget();
file1.FileName = "${basedir}/file1.txt";
FileTarget file2 = new FileTarget();
file2.FileName = "${basedir}/file2.txt";
RoundRobinTarget target = new RoundRobinTarget();
target.Targets.Add(file1);
target.Targets.Add(file2);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#45. SplitGroup
using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrapper;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
FileTarget file1 = new FileTarget();
file1.FileName = "${basedir}/file1.txt";
FileTarget file2 = new FileTarget();
file2.FileName = "${basedir}/file2.txt";
SplitTarget target = new SplitTarget();
target.Targets.Add(file1);
target.Targets.Add(file2);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#45. Trace
using System;
using NLog;
using NLog.Targets;
using System.Diagnostics;
class Example
{
static void Main(string[] args)
{
Trace.Listeners.Add(new ConsoleTraceListener());
TraceTarget target = new TraceTarget();
target.Layout = "${message}";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Debug("log message");
}
}
#46. WebService
using NLog;
using NLog.Targets;
class Example
{
static void Main(string[] args)
{
WebServiceTarget target = new WebServiceTarget();
target.Url = "http://localhost:2648/Service1.asmx";
target.MethodName = "HelloWorld";
target.Namespace = "http://www.nlog-project.org/example";
target.Protocol = WebServiceTarget.WebServiceProtocol.Soap11;
target.Parameters.Add(new MethodCallParameter("n1", "${message}"));
target.Parameters.Add(new MethodCallParameter("n2", "${logger}"));
target.Parameters.Add(new MethodCallParameter("n3", "${level}"));
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("Example");
logger.Trace("log message 1");
logger.Debug("log message 2");
logger.Info("log message 3");
logger.Warn("log message 4");
logger.Error("log message 5");
logger.Fatal("log message 6");
}
}
二、效果图:
三、参考:
https://nlog-project.org/documentation/v5.0.0/html/R_Project_NLog.htm
https://nlog-project.org/2022/05/16/nlog-5-0-finally-ready.html
https://nlog-project.org/download/