C# 使用 NLog 输出日志到文件夹

  1. 在项目中使用 NuGet 安装 NLog 包以及 NLog.Config

在这里插入图片描述

  1. 配置 nlog.config

在项目的根目录下创建一个 Nlog.config 文件(如果还没有),然后添加如下配置:

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- 定义日志目标 async="true" 异步写日志-->
	<targets async="true">
    <!-- log_file 配置,按天生成日志文件夹,保留时间7-->
    <target name="log_file" xsi:type="File"
            fileName="logs/${shortdate}/LogFile_${shortdate}.log"
            layout="${longdate}|${level:uppercase=true}|${message}${onexception:${newline}${exception:format=tostring}}${newline}"
            archiveEvery="Day"
            archiveNumbering="Rolling"
            maxArchiveDays="7"
            archiveAboveSize="5242880"
            keepFileOpen="false"
            concurrentWrites="true" />
    <!-- err_file 配置 -->
    <target name="err_file" xsi:type="File"
            fileName="logs/${shortdate}/ErrorFile_${shortdate}.log"
            layout="${longdate}|${level:uppercase=true}|${message}${onexception:${newline}${exception:format=tostring}}${newline}"
            archiveEvery="Day"
            archiveNumbering="Rolling"
            archiveAboveSize="5242880"
            maxArchiveDays="7"
            keepFileOpen="false"
            concurrentWrites="true" />
	</targets>
	  <!-- 定义日志规则 -->
	<rules>
	 <!-- 将所有输出日志和错误日志分别写入 log_file 和 err_file-->
		<logger name="*" minlevel="Debug"  writeTo="log_file" />
		<logger name="*" minlevel="Error"  writeTo="err_file" />
	</rules>
</nlog>

实现异步写入的另外一种配置:

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
	<targets>
    <!-- log_file 配置,按天生成日志文件夹,保留时间7-->
    <target  name="logfile"  xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
      <target xsi:type="File"
            fileName="logs/${shortdate}/ZJNLogFile_${shortdate}.log"
            layout="${longdate}|${level:uppercase=true}|${message}${onexception:${newline}${exception:format=tostring}}${newline}"
            archiveEvery="Day"
            archiveNumbering="Rolling"
            maxArchiveDays="7"
            archiveAboveSize="5242880"
            keepFileOpen="false"
            concurrentWrites="true" />
    </target>
    <target  name="errfile"  xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
      <!-- err_file 配置 -->
      <target xsi:type="File"
              fileName="logs/${shortdate}/ZJNErrorFile_${shortdate}.log"
              layout="${longdate}|${level:uppercase=true}|${message}${onexception:${newline}${exception:format=tostring}}${newline}"
              archiveEvery="Day"
              archiveNumbering="Rolling"
              archiveAboveSize="5242880"
              maxArchiveDays="7"
              keepFileOpen="false"
              concurrentWrites="true" />
    </target>

  </targets>
	<rules>
		<logger name="*" minlevel="Debug"  writeTo="logfile" />
		<logger name="*" minlevel="Error"  writeTo="errfile" />
	</rules>
</nlog>

配置说明:

  • fileName 属性: 使用 ${shortdate} 占位符来按天生成文件夹和日志文件名。例如,logs/${shortdate}/Logfile_${shortdate}.log 将创建一个名为 logs/2024-08-03/ 的文件夹,并在其中创建 Logfile_2024-08-03.log 文件。

  • layout属性:日志内容输出的模板

  • archiveEvery="Day": 这表示每天生成一个新的日志文件。

  • archiveNumbering="Rolling": 日志文件归档使用滚动编号,避免创建大量的备份文件。

  • maxArchiveFiles="30": 指定最多保留 30 个归档文件。如果不设置或者maxArchiveFiles值等于0,则不删除旧文件。不设置默认值:0

  • keepFileOpen="false"concurrentWrites="true": 这些设置确保文件可以在多个进程中安全写入,同时不保持文件句柄打开。

  • archiveAboveSize=“5242880”: 文件归档大小尺寸,如果单文凭超过 5242880,则重新创建一个新的文件

  • maxArchiveDays="7": 保留日志归档文件最长期限。通过设置 ·maxArchiveDays·,可以实现自动管理日志文件的归档和清理,避免日志文件过多导致存储空间的浪费。

  1. 在代码中初始化 NLog
using NLog;

class Program
{
    private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        Logger.Info("Application started.");

        // 其他代码...
    }
}

或者创建一个共用的写日志静态类,需要输出日志的代码逻辑处,通过调用当前静态类即可。

public static class Logger
{
    private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    public static void Write(string message)
    {
        try
        {
            if (logger.IsInfoEnabled) // 检查日志级别是否启用
            {
                logger.Info(message);
            }
        }
        catch (Exception ex)
        {
            // 记录异常到日志中,避免掩盖潜在问题
            NLog.LogManager.GetLogger("ExceptionLogger").Error(ex, "Logging failed in Write method.");
        }
    }

    public static void WriteDebug(string message)
    {
        try
        {
            if (logger.IsDebugEnabled) // 检查日志级别是否启用
            {
                logger.Debug(message);
            }
        }
        catch (Exception ex)
        {
            // 记录异常到日志中,避免掩盖潜在问题
            NLog.LogManager.GetLogger("ExceptionLogger").Error(ex, "Logging failed in WriteDebug method.");
        }
    }

    public static void Write(Exception ex)
    {
        try
        {
            logger.Error(ex);
        }
        catch (Exception innerEx)
        {
            // 记录异常到日志中,避免掩盖潜在问题
            NLog.LogManager.GetLogger("ExceptionLogger").Error(innerEx, "Logging failed in Write(Exception ex) method.");
        }
    }
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小丫头呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值