XYS.Utils.Log4Net 2.6.0

dotnet add package XYS.Utils.Log4Net --version 2.6.0
                    
NuGet\Install-Package XYS.Utils.Log4Net -Version 2.6.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="XYS.Utils.Log4Net" Version="2.6.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="XYS.Utils.Log4Net" Version="2.6.0" />
                    
Directory.Packages.props
<PackageReference Include="XYS.Utils.Log4Net" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add XYS.Utils.Log4Net --version 2.6.0
                    
#r "nuget: XYS.Utils.Log4Net, 2.6.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package XYS.Utils.Log4Net@2.6.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=XYS.Utils.Log4Net&version=2.6.0
                    
Install as a Cake Addin
#tool nuget:?package=XYS.Utils.Log4Net&version=2.6.0
                    
Install as a Cake Tool

XYS.Utils.Log4Net

基于 log4net 的日志工具类库。提供四种调用方式,输出统一走同一份 xys.log4net.config.xml:

  1. 静态门面 LogUtil —— 无需注入,历史代码零改动。
  2. 模块 logger ModuleLogger / ModuleLogger<T> —— 一次绑定 prefix(+可选 typeName),调用处只写 Log.Info("...")。
  3. 依赖注入 ILogUtil —— DI 场景可注入、可替换、便于单测。
  4. Microsoft.Extensions.Logging 桥接 —— 让标准 ILogger<T> 输出到同一份 log4net 配置。

目标框架

net8.0 · net462 · netcoreapp3.1 · netstandard2.0 · netstandard2.1

依赖


配置

程序集在加载时通过特性自动读取 log4net 配置:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xys.log4net.config.xml", Watch = true)]
  • 配置文件名固定为 xys.log4net.config.xml,需放在应用程序运行目录下(相对基目录解析)。
  • Watch = true:运行时修改配置会被自动重新加载。
  • 静默失败:若配置文件缺失或未定义 appender,log4net 不会报错,而是不产生任何日志输出。部署时请确认该文件已随程序一同发布。
  • 与加载顺序无关(2.6.0 起):log4net 只在某程序集首次创建默认仓库时处理其 [XmlConfigurator] 特性。若宿主(或其引用的第三方库)先于本库使用 log4net 且自身未配置,2.5.0 及以前本库的配置文件将永远不会加载、日志全部丢失。现在本库首次取 logger 时会兜底:仓库仍未配置且配置文件存在,就显式加载并监视它;宿主已自行配置的仓库保持原样,不覆盖、不叠加。宿主无需再为此在自己的程序集上重复声明 [assembly: XmlConfigurator(...)](已声明的也不受影响)。

logger 命名规则

每条日志按 {前缀}{级别后缀} 解析 logger,后缀为 -Debug / -Info / -Warn / -Error / -Fatal。例如前缀传 Order,Error 级别日志会写入名为 Order-Error 的 logger。可在配置中按此命名把不同来源、不同级别的日志分流到不同文件。

ILogger<T> 桥接使用另一套命名(logger 名 = 类型全名 Foo.Bar.MyService),但共用同一 log4net 仓库,可在 root 上挂 appender 让两套一起落盘。

布局中不要使用位置信息

%class / %C、%method / %M、%line / %L、%location / %l、%file / %F 依赖 log4net 的调用栈遍历:经本库封装后,它们指向本库内部(如 Log4NetLogUtil.Write)而不是业务代码,且 Release 下的方法内联会让结果不稳定,栈遍历本身开销也很大。类型名与方法名已由本库写在日志正文的前两列,请直接使用 %message。


LogUtil(静态门面)

命名空间 XYS.Utils.Log4Net。提供 Debug / Info / Warn / Error / Fatal 五个级别,每级均含普通、含异常、格式化三类重载。

using XYS.Utils.Log4Net;

// 最简:仅传前缀与内容,方法名由 [CallerMemberName] 自动填充
LogUtil.Info("Order", "订单创建成功");

// 记录异常
try { /* ... */ }
catch (Exception ex)
{
    LogUtil.Error("Order", "订单创建失败", ex);
}

// 显式指定类型名 / 方法名
LogUtil.Warn("Order", nameof(OrderService), "Create", "库存不足");

// 格式化日志
LogUtil.InfoFormat("Order", nameof(OrderService), "Create", "订单 {0} 金额 {1}", orderId, amount);

日志正文格式为:类型名(左对齐32) 方法名(左对齐24)-内容,便于日志按列对齐阅读。

⚠️ 不要把格式化参数传给非 Format 重载:LogUtil.Info("Order", "订单 {0} 创建", orderNo) 能编译通过,但 orderNo 会被绑定到自动填充方法名的 methodName 参数——方法名列变成订单号,{0} 原样输出。Log.Error("失败", ex.Message) 同理。请用字符串插值 $"订单 {orderNo} 创建" 或 *Format 重载。本包自带分析器 XYSLOG001 会在编译期对此告警,见下文「编译期检查」。


ModuleLogger(前缀绑定的模块 logger)

一次绑定 prefix(+可选 typeName),后续调用无需重复传,方法名由 [CallerMemberName] 自动填充。适合替换项目里那种「静态 LoggerName = "XX"、每次 LogUtil.Info(LoggerName, typeof(This).FullName, method, msg)」的手写包装。

using XYS.Utils.Log4Net;

public sealed class OrderService
{
    // 泛型糖:typeName 自动 = typeof(OrderService).FullName
    private static readonly ModuleLogger<OrderService> Log = LogUtil.ForModule<OrderService>("Order");

    public void Create(long id)
    {
        Log.Info($"创建订单 {id}");                    // method = "Create"(自动)
        try { /* ... */ }
        catch (Exception ex) { Log.Error("订单创建失败", ex); }
    }
}

四种入口按需选用:

var m1 = LogUtil.ForModule("Order");                              // 只绑 prefix
var m2 = LogUtil.ForModule("Order", "MyType");                    // 绑 prefix + 显式 typeName
var m3 = LogUtil.ForModule("Order", typeof(OrderService));        // 绑 prefix + Type
var m4 = LogUtil.ForModule<OrderService>("Order");                // 绑 prefix + 泛型 T(推荐)

DI 注入版:

public sealed class OrderService
{
    private readonly ModuleLogger<OrderService> _log;
    public OrderService(ILogUtil log) => _log = log.ForModule<OrderService>("Order");

    public void Create() => _log.Info("创建订单");
}
  • 内部委托到 ILogUtil,与静态 LogUtil、DI 注入路径共用同一 log4net 配置与行为(换个 ILogUtil 实现即可整体替换/静默)。
  • 绑定 Type / 泛型 T 时,typeName 规则与 ILogger<T> 分类名一致:命名空间 + 类型名,嵌套类型用 . 分隔(Ns.Outer.Inner),泛型去掉类型参数(Generic<int> → Ns.Generic),避免 Type.FullName 的 + 与带程序集版本的长串撑破列对齐。
  • 全部 Debug / Info / Warn / Error / Fatal 及 *Format 重载均具备,日志正文格式与静态版一致。
  • ⚠️ *Format 变体不自动捕获调用方法名:非 Format 方法靠 [CallerMemberName] 自动填充方法名,而 *Format 因末尾 params 参数限制无法自动捕获,日志的方法名列会为空。需要方法名时用非 Format 重载(如 Log.Info($"订单 {id}"));*Format 的价值在于级别关闭时可跳过 string.Format(延迟格式化,热路径更省)。

ILogUtil(依赖注入)

需要注入的场景使用 ILogUtil 接口,实现为 Log4NetLogUtil。静态门面与 DI 注入共用同一单例 Log4NetLogUtil.Default,行为完全一致,因此可以逐步迁移,两种风格共存。

using Microsoft.Extensions.DependencyInjection;
using XYS.Utils.Log4Net;

// 启动时注册
services.AddXysLog4Net();

// 消费方按注入使用;便捷扩展方法镜像静态 API 的全部重载
public sealed class OrderService
{
    private readonly ILogUtil _log;
    public OrderService(ILogUtil log) => _log = log;

    public void Create(long id)
    {
        _log.Info("Order", $"创建订单 {id}");
        try { /* ... */ }
        catch (Exception ex)
        {
            _log.Error("Order", nameof(OrderService), nameof(Create), "订单创建失败", ex);
        }
    }
}

本库的 XYS.Utils.Log4Net.LogLevel 与 Microsoft.Extensions.Logging.LogLevel 同名:同一文件同时 using 两个命名空间并直接写 LogLevel 时会报 CS0104 歧义。为保持兼容不改名,请用别名区分,如 using XysLogLevel = XYS.Utils.Log4Net.LogLevel;。

单测可自定义假实现替换:

services.AddSingleton<ILogUtil>(new NullLogUtil());  // 或 Moq 生成的模拟

Microsoft.Extensions.Logging 桥接

让使用标准 ILogger<T> 的代码也走同一份 log4net 配置:

using Microsoft.Extensions.Logging;
using XYS.Utils.Log4Net.Logging;

services.AddLogging(builder =>
{
    builder.AddXysLog4Net();
});

// 消费方
public sealed class ReportService
{
    private readonly ILogger<ReportService> _log;
    public ReportService(ILogger<ReportService> log) => _log = log;

    public void Run()
    {
        _log.LogInformation("开始生成报表");           // 走 log4net → xys.log4net.config.xml
        _log.LogError(ex, "报表生成失败: {Id}", id);
    }
}
  • 级别映射:Trace → TRACE,Debug → DEBUG,Information → INFO,Warning → WARN,Error → ERROR,Critical → FATAL,None 关闭。

    2.6.0 起 Trace 映射到 log4net 的 TRACE(2.5.0 映射为 DEBUG):配置为 DEBUG 时不再混入框架的大量 Trace 日志;确需 Trace 时把对应 logger 级别设为 TRACE 或 ALL。

  • logger 命名:使用 ILogger 的分类名(ILogger<Foo.Bar.ReportService> → logger 名 Foo.Bar.ReportService),可在 log4net 配置中按类型名分流。

  • EventId:非零或具名的 EventId 写入 log4net 事件属性 EventId / EventName,布局里用 %property{EventId}、%property{EventName} 输出。

  • 提供程序别名 Log4Net:可在 appsettings.json 中按别名单独设置过滤级别:

    "Logging": {
      "LogLevel": { "Default": "Information" },
      "Log4Net": { "LogLevel": { "Default": "Warning", "MyApp.Orders": "Information" } }
    }
    
  • BeginScope:首版未接 log4net 的 NDC/LogicalThreadContext,返回 no-op。

  • 与 LogUtil / ILogUtil 使用同一 log4net 仓库,只要 xys.log4net.config.xml 的 root 挂上 appender,两套 logger 命名的日志都会被输出。


健壮性

日志记录不会因参数问题打断业务调用方:

  • logPrefix / typeName / methodName / info 为 null 时按空串处理,不抛 NullReferenceException。
  • *Format 系列格式化失败时(格式串为 null、占位符与参数不匹配、参数的 ToString() 抛异常等)退化为输出原始格式串,不向上抛出。
  • 传入未定义的 LogLevel 值(如 (LogLevel)99)时静默忽略,不再抛 IndexOutOfRangeException。

性能

  • 按前缀缓存各级别的 log4net ILog,并显式绑定本程序集仓库:热路径上没有 logger 名字符串拼接,也没有 Assembly.GetCallingAssembly() 栈遍历。
  • 各级别在写入前先判断 IsXxxEnabled,未启用的级别零分配短路(2.5.0 每次调用约 600ns + 48B,2.6.0 约 60ns + 0B)。
  • 配置热重载(Watch = true)后缓存的 logger 依然有效,级别判断是实时的。

编译期检查(XYSLOG001)

NuGet 包内含 Roslyn 分析器(analyzers/dotnet/cs),以 PackageReference 引用本包即自动启用:

ID 级别 说明
XYSLOG001 Warning 实参被显式传给了本库日志方法中自动捕获方法名的 [CallerMemberName] 参数,通常是把格式化参数误传给了非 Format 重载
LogUtil.Info("Order", "订单 {0} 创建", orderNo);   // ⚠ XYSLOG001
Log.Error("失败", ex.Message);                     // ⚠ XYSLOG001
LogUtil.Info("Order", $"订单 {orderNo} 创建");      // ✓
LogUtil.InfoFormat("Order", nameof(OrderService), nameof(Create), "订单 {0}", orderNo); // ✓

确需自定义方法名时,改用显式含 typeName, methodName 参数的 4/5 参数重载,或用 #pragma warning disable XYSLOG001 抑制。

以 ProjectReference 引用本项目的同解决方案项目不会自动获得分析器;如需启用,另加 <ProjectReference Include="..\XYS.Utils.Log4Net.Analyzers\XYS.Utils.Log4Net.Analyzers.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />。


版本

当前版本 2.6.0。

  • 2.6.0:修复宿主先于本库使用 log4net 时配置不加载、日志全部丢失;*Format 及非法级别不再抛异常;缓存 logger,关闭级别零分配短路;新增 XYSLOG001 分析器;新增测试项目 XYS.Utils.Log4Net.Tests。 ILogger 桥接:Trace 改映射 log4net TRACE(行为变化,见上文)、EventId 写入事件属性、新增提供程序别名 Log4Net。 ModuleLogger 的 typeName 改用与 ILogger<T> 一致的显示名(行为变化:仅影响嵌套/泛型类型)。随包输出 XML 文档注释。
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (26)

Showing the top 5 NuGet packages that depend on XYS.Utils.Log4Net:

Package Downloads
XYS.FR

Package Description

XYS.DataFactory

Package Description

XYS.Utils.DB

Package Description

XYS.Utils.Web

Package Description

XYS.Lab.Report

Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.6.0 99 11/16/2026
2.5.0 446 7/24/2026
2.3.2 181 7/23/2026
2.3.1 387 7/14/2026
2.1.1.1 1,306 12/2/2023
2.1.0.3 1,923 11/23/2022
2.1.0.2 1,851 9/13/2022
2.1.0.1 7,484 1/23/2022
2.0.2.2 6,633 12/21/2021
2.0.2.1 1,694 12/20/2021
2.0.1.5 1,139 12/20/2021
2.0.1.4 13,155 5/31/2021
2.0.1.3 5,088 5/10/2021
2.0.1.2 920 5/10/2021
2.0.1.1 1,271 4/22/2021
2.0.0.1 1,360 2/20/2021
1.0.3.2 613 2/8/2021
1.0.3.1 599 2/8/2021
1.0.2.4 614 2/7/2021
Loading failed