.NET 项目实战:NLog 日志框架配置与封装
在 .NET 开发中,选择合适的日志框架至关重要。相比于 Log4Net,NLog 以其灵活的配置和强大的扩展性受到许多开发者的青睐。本文将介绍如何在项目中集成 NLog,配置核心规则,并封装一个通用的日志调用类以提升开发效率。
引入依赖
首先通过 NuGet 包管理器安装 NLog 和 NLog.Config 包。确保项目引用了必要的程序集。
配置文件详解
建议新建独立的 NLog.config 文件进行配置,避免与 web.config 或 appsettings.json 混用导致维护困难。以下是经过优化的配置示例,支持异步文件写入和彩色控制台输出。
<?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 name="asyncFile" xsi:type="AsyncWrapper">
<target name="log_file" xsi:type="File"
fileName="${basedir}/ProjectLogs/${shortdate}/${logger}-${level}-${shortdate}.txt"
layout="${longdate} | ${message}${onexception:${exception:format=message}}\n${newline}\n${stacktrace}"
archiveFileName="${basedir}/archives/${logger}-${level}-${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen= />


