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


结尾

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

相关推荐
lly20240616 小时前
Bootstrap 警告框
开发语言
2601_9491465317 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧17 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX17 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010317 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎18 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE18 小时前
PHP纹路验证码
开发语言·php
仟濹18 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥18 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
Re.不晚18 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言