.net 标准 1.3 项目中的 log4net 配置

log4net configuration in .net standard 1.3 project

我正在尝试将 c# 项目从 .net Framework v4.6 迁移到 .net 标准。 该项目有 log4net v2.0.8 依赖。

我找到这个 , which recommends to use .net standard 1.3 and gives reference to this post 以获得更详细的解决方案。

使用XmlConfigurator.Configure方法配置log4net时出现问题,需要ILoggerRepository作为第一个参数。

在post中使用了LogManager.GetRepository(Assembly.GetEntryAssembly())方法,但是Assembly.GetEntryAssembly()在.net standard 1.3中是not supported

Official documentation 也被破坏了,因为 XmlConfigurator.Configure 方法签名和它的示例用法不匹配。

那么,如何在 .net standard 1.3 项目中配置 log4net?

在您的 .NET Standard 1.3 class 库项目中,在负责 Log4net 配置的方法签名中提供一个 Assembly 参数,例如:

public static void Configure(Assembly assembly)
{
    ILoggerRepository repository = LogManager.GetRepository(assembly);
    XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

    // ...
}

从您的实际应用程序调用此方法,在完整的 .NET Framework 或 .NET Core 中开发,通过例如 Assembly.GetEntryAssembly().

传入此 Assembly 参数

Assembly.GetEntryAssembly() 在完整的 .NET Framework 和 .NET Core 中均受支持。