.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 两个子目录,用于存放不同业务模块的日志文件。


结尾

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

相关推荐
用户298698530142 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
牧马人win2 天前
SmartDapper.Repository
.net
mudtools3 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的3 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django