在 C# WinForm 中使用 NLog 记录日志,需要进行以下步骤:

  1. 添加 NLog 库。可以通过 NuGet 包管理器,搜索并安装 NLog。

  2. 在项目中添加一个 NLog 的配置文件,命名为 NLog.config。该配置文件用于指定日志输出的目标和格式等信息。示例配置文件如下:

<?xml version='1.0' encoding='utf-8'?>
<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
      autoReload='true'
      internalLogLevel='Info'
      internalLogFile='c:\temp\nlog-internal.log'>

  <targets>
    <target name='file' xsi:type='File' fileName='c:\temp\nlog-logfile.txt' />
    <target name='console' xsi:type='Console' />
  </targets>

  <rules>
    <logger name='*' minlevel='Trace' writeTo='file' />
    <logger name='*' minlevel='Trace' writeTo='console' />
  </rules>
</nlog>
  1. 在程序启动时,调用 NLog 的配置方法,加载配置文件。在 WinForm 的入口函数中,可以添加如下代码:
using NLog;

static class Program
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    [STAThread]
    static void Main()
    {
        LogManager.LoadConfiguration('NLog.config');
        Logger.Info('Application starts');

        // 启动 WinForm 应用程序
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());

        Logger.Info('Application exits');
    }
}
  1. 在需要记录日志的地方,使用 NLog 的 Logger 对象进行日志记录。示例代码如下:
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

private void Button_Click(object sender, EventArgs e)
{
    Logger.Info('Button clicked');
}

通过以上步骤,就可以在 C# WinForm 中使用 NLog 进行日志记录了。日志会同时输出到文件和控制台。可以根据需要修改 NLog 配置文件,调整日志输出的格式和目标。


原文地址: https://www.cveoy.top/t/topic/qmSx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录