Microsoft.Extensions.Logging.Log4Net.AspNetCore 10.0.0

dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 10.0.0
                    
NuGet\Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 10.0.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="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="10.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="10.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" />
                    
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 Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 10.0.0
                    
#r "nuget: Microsoft.Extensions.Logging.Log4Net.AspNetCore, 10.0.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 Microsoft.Extensions.Logging.Log4Net.AspNetCore@10.0.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=Microsoft.Extensions.Logging.Log4Net.AspNetCore&version=10.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Microsoft.Extensions.Logging.Log4Net.AspNetCore&version=10.0.0
                    
Install as a Cake Tool

Microsoft.Extensions.Logging.Log4Net.AspNetCore

Allows to configure Log4net as Microsoft Extensions Logging handler on any ASP.NET Core application.

Thanks to @anuraj for this original blog post.

Release Build NuGet

GitHub Actions deployment

The documented release workflow runs in GitHub Actions. It builds, tests, and packs the NuGet package on main and on manual dispatch.

If you want assembly signing to remain enabled in GitHub, add these repository secrets:

  • SIGNING_SNK_BASE64 for Microsoft.Extensions.Logging.Log4Net.AspNetCoreKey.snk
  • SIGNING_PFX_BASE64 for the companion private certificate file, if you want to keep that asset available privately
  • SIGNING_PUBLIC_KEY_BASE64 for the public key file, if you want to keep that asset available privately

The workflow restores any configured signing assets into the runner at runtime; none of the signing files need to be committed to the repository.

Example of use

  • Install the package or reference the project into your asp.net core application.

  • Add the AddLog4Net() call into your Configure method of the Startup class.

using Microsoft.Extensions.Logging;

public class Startup
{
    //...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...

        loggerFactory.AddLog4Net(); // << Add this line
        app.UseMvc();

        //...
    }
}
  • For dotnet 6.0 and later add builder.Logging.AddLog4Net(); call in your Program.cs file.

  • Add a log4net.config file with the content:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
  </root>
</log4net>

You can found more configuration examples on configuration documentation.

FAQ

Using BeginScope

Associated issues #45

From version 2.2.7, this nuget allow to use the BeginScope method from Log4NetLogger.

var dictionary = new Dictionary<string, string>() { { "test", "SCOPED_VALUE" } };
using (var scope = logger.BeginScope(dictionary))
{
    logger.LogCritical(message);
}

The BeginScope method allow any object, but only some of types are handled in an special way. Those types are:

  • string
  • IEnumerable<KeyValuePair<string, string>>
  • IEnumerable<KeyValuePair<string, object>>
  • ValueTuple<string, T> where T is string, any numeric type or object

By default, any other type will be managed as a conventional object.

How it works

When you use any of the IEnumerable<KeyValuePair<,>> allowed types, the collection will be processed and every item from this collection should be introduced to the LogicalThreadContext managed by the log4net library using the Key as the property name and the Value as the value to replace the placeholder on the Pattern Layout defined.

This example shows how the log4net.config pattern layout could include a %property{} placeholder that will be matched within the corresponding scoped value from the collection argument.

<layout type="log4net.Layout.PatternLayout">
    
    <conversionPattern value="%date [%thread] %-5level %logger %ndc - scope=%property{scope} - %property{custom_name} - %message%newline" />
</layout>

When you use the BeginScope method passing a collection that contains a KeyValuePair within the key custom_name, the logged message will contain the SCOPED_VALUE text on it.

var dictionary = new Dictionary<string, string>() { { "custom_name", "SCOPED_VALUE" } };
using (var scope = logger.BeginScope(dictionary))
{
    logger.LogCritical(message); // SCOPED_VALUE will replace the %property{custom_name} placeholder
}

At the other hand, if the argument is not from the given IEnumerable<KeyValuePair<,>>, the value will be logged on the default scope property.

using (var scope = logger.BeginScope("SCOPED_VALUE"))
{
    logger.LogCritical(message); // SCOPED_VALUE will replace the %property{scope} placeholder
}

using (var scope = logger.BeginScope(Guid.NewGuid()))
{
    logger.LogCritical(message); // Guid value will replace the %property{scope} placeholder
}

And, when you use two chained BeginScope calls...

using (var scope = logger.BeginScope("SCOPED_VALUE"))
{
    using (var scope = logger.BeginScope(Guid.NewGuid()))
    {
        logger.LogCritical(message); // SCOPED_VALUE and Guid value (both) will replace the %property{scope} placeholder
    }
}

For additional information about how the LogicalThreadContext works, please visit the official documentation

.NET Core 2.0 - Logging debug level messages

Associated issues #34 & #41

In order to be able to register Debug level messages in any of your configured log4net appenders, you should change the ASP .NET Core 2 configuration when you build your IWebHost instance as follows.

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .ConfigureLogging((hostingContext, logging) =>
            {
              // The ILoggingBuilder minimum level determines the
              // the lowest possible level for logging. The log4net
              // level then sets the level that we actually log at.
              logging.AddLog4Net();
              logging.SetMinimumLevel(LogLevel.Debug);
            })
            .Build();

Logging lower than the Information Level

Associated issues #85

Also note that when trying to allow for levels messages below the Information level for a development build you must make allowances for it in the appsettings.Development.json as specified in the documentation and illustrated below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
	  "...":"..."
    }
  }
}

Modifying logging behaviour

In many cases you can modfiy the logging behaviour of the provider to fit your own needs. See modifying logging behaviour for more information.

Special thanks

Thank you very much to all contributors & users by its collaboration, and specially to:

  • @twenzel by his great job on adapting the library to the new logging recomendations for .NET Core 2.
  • @sBoff by the fix of the mutiple calls to XmlConfigurator.Configure issue.
  • @kastwey by the feature to allow to replace values of log4net.config using the Microsoft.Extensions.Configuration.
  • @willwolfram18 by bugfixing Log4NetScopeFactory usage when provided in Log4NetProviderOptions.
  • @lscorcia by the fix of incorrect call stack when logging.
  • @JustusGreiberORGADATA by the inclusion of a configurable logging event factory, and IExternalScope provider implementation.
  • @Radim Holek for enabling ValueTuple mapping in scopes.
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  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 is compatible.  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 is compatible.  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 is compatible.  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 was computed.  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 (120)

Showing the top 5 NuGet packages that depend on Microsoft.Extensions.Logging.Log4Net.AspNetCore:

Package Downloads
Dywham.Commons.Messaging.NServiceBus

Package Description

Log4ALA

Log4Net appender fo Azure Log Analytics (ALA)... sending data to Azure Log Analytics. The data will also be logged/sent asynchronously for high performance and to avoid blocking the caller thread.

Bnsights.Core

Package Description

AxeAccessibilityDriver

Run Axe for accessibilty scan Output results into json, csv and WATR report

VNPT.iNRES.Common

VNPT iNRES Common

GitHub repositories (18)

Showing the top 18 popular GitHub repositories that depend on Microsoft.Extensions.Logging.Log4Net.AspNetCore:

Repository Stars
anjoy8/Blog.Core
💖 ASP.NET Core 8.0 全家桶教程,前后端分离后端接口,vue教程姊妹篇,官方文档:
lampo1024/DncZeus
DncZeus 是一个基于.NET 7 + Vue.js(iview-admin) 的前后端分离的通用后台权限(页面访问、操作按钮控制)管理系统框架。后端使用.NET 7 + EF Core构建,UI则是目前流行的基于Vue.js的iView(iview-admin)。项目实现了前后端的动态权限管理和控制以及基于JWT的用户令牌认证机制,让前后端的交互更流畅。码云镜像:https://gitee.com/rector/DncZeus 。演示地址(demo):
AElfProject/AElf
An AI-enhanced cloud-native layer-1 blockchain network. 
spring-projects/spring-net
Spring Framework for .NET
LGouellec/streamiz
.NET Stream Processing Library for Apache Kafka 🚀
Nihlus/Launchpad
An open-source game launcher for your games
migomiddle/xms
基于.netcore的跨平台应用框架,包含众多常用模块,易上手、易扩展,xms可理解为x(可扩展的/任意的)m(管理)s(系统)
junkai-li/NetCoreKevin
基于.NET搭建-AI知识库智能体-现代化Saas企业级前后端分离架构:前端Vue3、多缓存、自动任务、分布式、一库多租户、日志、授权和鉴权、CAP集成事件、SignalR、领域事件、MCP协议服务、IOC模块化注入、自动任务、多短信集成、AI、AgentFramework智能体、AISemanticKernel集成、RAG检索增强、本地离线AI模型调用、API多版本、单元测试、RabbitMQ、Skills技能使用、AI知识库、AI联网搜索
EtienneLamoureux/TQVaultAE
Extra bank space for Titan Quest Anniversary Edition
NakedObjectsGroup/NakedObjectsFramework
Implementation of the 'naked objects pattern' on .NET platform. Turns a POCO domain model (that follows a few simple conventions) into a complete application. See the ReadMe (at the bottom of this page) for more details.
qian-o/Dimension
基于 .NET 6 的在线音视频聊天项目
uyoufu/UZonMail
宇正群邮是一款开源的邮件群发软件,提供邮件群发、邮件营销(EDM)、邮箱采集、任意变量、AI 生成、多线程并发等功能。支持所有类型邮箱账号。原生企业级品质,支持多端用户,支持Windows、Linux、MacOS等操作系统, 支持服务器部署。已在外贸营销、教育培训、财务会计等多个行业广泛使用。 UZonMail is an open-source, enterprise‑grade bulk email and mass‑mailing platform designed for high‑volume EDM and email marketing campaigns. Widely adopted in industries such as education and finance
snowflakedb/snowflake-connector-net
Snowflake Connector for .NET
daohainam/mini-web-server
A simple but full-featured web server, supports HTTP/1, HTTP/2, MVC, API, Authentication, Authorization...
gnsilence/HangfireHttpJob
hangfire的拓展程序,在原作者基础上增加了一些功能,调用api的方式来执行定时任务
zhuyongzhengs/Rex.ShopMicroService.Sample
一个基于ABP Framework 10.0、PostgreSQL、MongoDB、Redis、RabbitMQ、CAP、ElasticSearch、Minio、YARP的微服务电商商城平台,采用主流的互联网技术架构、全新的UI设计、可视化布局、支持集群部署;拥有活动促销、优惠卷、商品秒杀等众多完整的营销功能。
AdrianStrugala/AvroConvert
Rapid Avro serializer for C# .NET
tntlinking-opensource/openhis
OpenHIS医院系统(通用版)是一款适用于公立二级以下医院、乡镇卫生院、社区卫生服务中心的综合性医院信息管理系统,包含体检、后台管理、收费结算、医护协同、药房、电子病历等10大功能模块,支持门诊、住院、医技、后勤各项核心业务。
Version Downloads Last Updated
10.0.0 2,841 5/5/2026
8.0.0 11,947,484 12/7/2023
7.0.0 798,845 10/16/2023
6.1.0 15,392,046 1/24/2022
6.0.0 1,000,100 11/10/2021
5.0.4 1,009,585 9/8/2021
5.0.3 1,085,807 6/15/2021
5.0.1 1,343,505 3/23/2021
5.0.0 1,403,637 11/15/2020
3.1.5 1,241,649 10/20/2020
3.1.3 408,832 9/21/2020
3.1.0 3,676,562 2/26/2020
3.0.3 1,356,657 11/12/2019
3.0.0 501,047 9/26/2019
2.2.12 593,390 8/21/2019
2.2.11 654,421 5/10/2019
2.2.10 881,780 1/14/2019
2.2.9 37,003 1/7/2019
2.2.8 29,066 1/2/2019
2.2.6 394,108 10/22/2018
Loading failed

#148 - Upgrade to .NET 9 and .NET 10