在 WinForms 應用程序中使用 NLog 記錄日志非常簡單。首先,確保已經安裝了 NLog 庫。如果尚未安裝,可以使用 NuGet 包管理器進行安裝:
Install-Package NLog
接下來,按照以下步驟配置和使用 NLog:
NLog.config
的配置文件。在此文件中,定義日志記錄的設置。例如:<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE config PUBLIC "-//NLog//DTD Config 1.0//EN" "http://nlog-project.org/dtds/nlog.dtd">
<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 http://nlog-project.org/dtds/nlog.dtd">
<targets>
<target name="file" xsi:type="File" fileName="logs/app.log" keepFileOpen="true" encoding="utf-8" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
這個配置文件將日志記錄到名為 app.log
的文件中,并始終保持文件打開。
Program.cs
文件中,引入 NLog 命名空間并配置 NLog:using System;
using System.Windows.Forms;
using NLog;
namespace WinFormsApp
{
static class Program
{
[STAThread]
static void Main()
{
// 初始化 NLog
var logger = LogManager.GetCurrentClassLogger();
logger.Info("Application started.");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
這里,我們使用 LogManager.GetCurrentClassLogger()
獲取當前類的日志記錄器實例,并使用 logger.Info()
記錄一條信息級別的日志。
MainForm.cs
中:using System;
using System.Windows.Forms;
using NLog;
namespace WinFormsApp
{
public partial class MainForm : Form
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
logger.Info("Button 1 clicked.");
MessageBox.Show("Button 1 clicked!");
}
}
}
在這個例子中,當用戶點擊按鈕時,我們記錄一條信息級別的日志。
現在,當您運行 WinForms 應用程序時,NLog 將根據 NLog.config
文件中的配置將日志記錄到文件中。