.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 文件夹,并分别创建 common 和 storefile 两个子目录,用于存放不同业务模块的日志文件。


结尾

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

相关推荐
旖旎夜光18 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
Jeff-Tsai19 小时前
手上的纸质单据,能不能直接变成系统里的表单?
ai·.net·blazor·erp
codeejun19 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑19 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者1 天前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员1 天前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇1 天前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu1 天前
python:DecisionTree
开发语言·后端·python·算法
geovindu1 天前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
炸膛坦客1 天前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++