.NET 6 NLog 实现多日志文件按业务模块拆分的实践

在项目开发过程中,如果把日志、异常和业务代码全部写在一起,后期维护会比较混乱。尤其是日志,一旦项目功能增多,所有信息都写到同一个文件中,查找问题会非常不方便。

因此在本项目中,对日志进行了简单拆分:日志类只负责记录日志,不和异常类、业务类混在一起,并且按业务模块分别写入不同的日志文件,提升日志的可读性和维护性。


一、安装 NLog

通过 NuGet 安装 NLog 相关包:

复制代码
Install-Package NLog Install-Package NLog.Config

安装完成后,项目中会使用 NLog 作为日志框架。


二、配置日志文件

1. 新建 NLog.config

在项目中新增 NLog.config 文件。

2. 设置文件属性

右键 NLog.config → 属性

"复制到输出目录" 设置为 "如果较新则复制",确保程序运行时能够正确读取配置。

3. 配置不同的日志文件

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">
	<!-- 定义全局变量 -->
	<variable name="logDir" value="${basedir}/logs" />
	<!-- 定义日志目标 -->
	<targets>
		<!-- 通用日志 -->
		<target xsi:type="File"
				name="commonFile"
				fileName="${logDir}/common/${shortdate}.log"
				layout="${longdate}${newline}${uppercase:${level}}${newline}${message}${newline}-----------------------------${newline}"
				concurrentWrites="true"
				keepFileOpen="false" />
		<!-- StoreFile 日志 -->
		<target xsi:type="File"
				name="storeFile"
				fileName="${logDir}/storefile/${shortdate}.log"
			    layout="${longdate}${newline}${uppercase:${level}}${newline}${message}${newline}-----------------------------${newline}"
			    concurrentWrites="true"
				keepFileOpen="false" />
	</targets>
	<!-- 定义规则 -->
	<rules>
		<!-- common 日志 -->
		<logger name="CommonLogger" minlevel="Info" writeTo="commonFile" />
		<!-- storefile 日志 -->
		<logger name="StoreLogger" minlevel="Info" writeTo="storeFile" />
	</rules>
</nlog>

三、编写日志类

日志类单独封装,只负责日志记录,不处理具体业务逻辑。

cs 复制代码
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StoreDb.Common.Helper
{
    /// <summary>
    /// 日志类
    /// </summary>
    public static class Logs
    {
        private static readonly Logger CommonLogger = LogManager.GetLogger("CommonLogger");
        private static readonly Logger StoreLogger = LogManager.GetLogger("StoreLogger");
        /// <summary>
        /// 保存到common日志
        /// </summary>
        /// <param name="message"></param>
        public static void Common(string message)
        {
            CommonLogger.Info(message);
        }
        /// <summary>
        /// 保存到store日志
        /// </summary>
        /// <param name="message"></param>
        public static void Store(string message)
        {
            StoreLogger.Info(message);
        }
        /// <summary>
        /// common异常
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public static void CommonError(string message, Exception ex = null)
        {
            CommonLogger.Error(ex, message);
        }
        /// <summary>
        /// store异常
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public static void StoreError(string message, Exception ex = null)
        {
            StoreLogger.Error(ex, message);
        }
    }
}

四、使用示例

cs 复制代码
Logs.Common("系统启动完成");
Logs.Store("执行业务操作");

程序运行后,会在项目根目录下自动生成 logs 文件夹,并分别创建 commonstorefile 两个子目录,用于存放不同业务模块的日志文件。


结尾

通过以上方式,实现了日志与业务、异常的解耦,并按业务模块对日志进行拆分。日志结构清晰,配置简单,方便后期问题排查和系统维护,适合在日常项目中使用。

相关推荐
丰锋ff29 分钟前
3.1 Qt事件之事件处理器
开发语言·qt
多弗朗皮卡丘43 分钟前
C语言梦开始的地方7:函数
c语言·开发语言
月华路1 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding2 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
m0_380743872 小时前
从零调用 Claude 教程
开发语言·python·node.js
起床学FPGA2 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
x_x-F3 小时前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php
名字还没想好☜3 小时前
Java 线上内存泄漏排查实战:jmap 导堆、MAT 找 GC Roots 与四类常见泄漏
java·开发语言·jvm·内存泄漏
码匠许师傅4 小时前
【C++ 面试真题】聊聊 C++ 的多继承与虚继承
开发语言·c++·面试
我不是疯子是傻子4 小时前
Qt CAN通信周期发送抖动?实测定时器精度校准与时间戳补偿方案
开发语言·数据库·qt