C#Nlog
时间: 2025-05-14 19:43:03 浏览: 46
### C# 中 NLog 的使用教程
#### 安装 NLog 库
为了在项目中使用 NLog,可以通过 NuGet 包管理器安装 `NLog` 和可选的 `NLog.Config`。这会帮助创建默认的配置文件 `NLog.config`[^1]。
如果不想使用自动生成的配置文件,则可以手动创建一个名为 `NLog.config` 的 XML 文件并将其放置于项目的根目录下。确保该文件设置为随应用程序一起复制到输出目录。
#### 创建 NLog 配置文件
以下是典型的 `NLog.config` 文件结构:
```xml
<?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">
<!-- 定义日志目标 -->
<targets>
<target xsi:type="File" name="logfile" fileName="${basedir}/logs/logfile.txt" />
<target xsi:type="Console" name="console" layout="${level}: ${message}" />
</targets>
<!-- 设置日志规则 -->
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile, console" />
</rules>
</nlog>
```
上述配置指定了两个日志目标:一个是写入磁盘的日志文件 (`logfile`),另一个是控制台输出 (`console`)。所有级别的日志都会被记录下来。
#### 在代码中初始化和使用 NLog
下面是一个简单的类示例,展示如何在 C# 代码中集成 NLog 并记录不同类型的日志消息:
```csharp
using System;
using NLog;
public class MyService
{
// 初始化静态 Logger 实例
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public void Execute()
{
try
{
// 记录信息级别日志
logger.Info("Starting the execution of MyService");
// 模拟业务逻辑
int result = PerformCalculation();
logger.Debug($"The calculation returned a value: {result}");
// 抛出异常以测试错误日志功能
if (result < 0)
throw new InvalidOperationException("Invalid operation detected!");
logger.Warn("This is a warning message.");
}
catch (Exception ex)
{
// 错误捕获与日志记录
logger.Error(ex, "An exception was thrown during service execution");
}
finally
{
logger.Info("Execution has been completed.");
}
}
private int PerformCalculation()
{
Random random = new Random();
return random.Next(-10, 10); // 可能返回负数
}
}
```
在此代码片段中:
- 使用了 `Info`, `Debug`, `Warn`, 和 `Error` 方法分别记录不同类型的消息。
- 当抛出异常时,调用了 `Error` 方法并将异常对象作为参数传递给它,以便更全面地捕捉上下文信息[^2]。
#### 处理高级场景
除了基本的日志记录外,还可以进一步优化 NLog 的使用方式,比如:
- **自动清理旧日志**:通过配置实现日志归档和过期删除策略。
- **多线程支持**:利用异步目标提高性能。
- **依赖注入扩展**:将 NLog 整合至 DI 容器中简化全局访问[^3]。
---
阅读全文
相关推荐


















