XYS.Utils.Log4Net 2.5.0

dotnet add package XYS.Utils.Log4Net --version 2.5.0
                    
NuGet\Install-Package XYS.Utils.Log4Net -Version 2.5.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.5.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.5.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.5.0
                    
#r "nuget: XYS.Utils.Log4Net, 2.5.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.5.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.5.0
                    
Install as a Cake Addin
#tool nuget:?package=XYS.Utils.Log4Net&version=2.5.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 不会报错,而是不产生任何日志输出。部署时请确认该文件已随程序一同发布。

logger 命名规则

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

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


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)-内容,便于日志按列对齐阅读。


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 实现即可整体替换/静默)。
  • 全部 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);
        }
    }
}

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

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/DebugDEBUGInformationINFOWarningWARNErrorERRORCriticalFATALNone 关闭。
  • logger 命名:使用 ILogger 的分类名(ILogger<Foo.Bar.ReportService> → logger 名 Foo.Bar.ReportService),可在 log4net 配置中按类型名分流。
  • BeginScope:首版未接 log4net 的 NDC/LogicalThreadContext,返回 no-op。
  • LogUtil / ILogUtil 使用同一 log4net 仓库,只要 xys.log4net.config.xml 的 root 挂上 appender,两套 logger 命名的日志都会被输出。

健壮性

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

  • typeName / methodNamenull 时按空串处理,不抛 NullReferenceException
  • *Format 系列在格式串与参数不匹配时捕获 FormatException,退化为输出原始格式串,不向上抛出。
  • 各级别在写入前先判断 IsXxxEnabled,未启用的级别直接短路,避免无谓的字符串拼接与格式化开销。

版本

当前版本 2.5.0

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.5.0 254 7/24/2026
2.3.2 148 7/23/2026
2.3.1 353 7/14/2026
2.1.1.1 1,248 12/2/2023
2.1.0.3 1,898 11/23/2022
2.1.0.2 1,824 9/13/2022
2.1.0.1 7,462 1/23/2022
2.0.2.2 6,610 12/21/2021
2.0.2.1 1,673 12/20/2021
2.0.1.5 1,120 12/20/2021
2.0.1.4 13,122 5/31/2021
2.0.1.3 5,059 5/10/2021
2.0.1.2 900 5/10/2021
2.0.1.1 1,252 4/22/2021
2.0.0.1 1,341 2/20/2021
1.0.3.2 594 2/8/2021
1.0.3.1 582 2/8/2021
1.0.2.4 596 2/7/2021
1.0.2.3 603 2/7/2021
Loading failed