Aicrosoft.Extensions.NLog 8.0.0-beta.260130.2

This is a prerelease version of Aicrosoft.Extensions.NLog.
dotnet add package Aicrosoft.Extensions.NLog --version 8.0.0-beta.260130.2
                    
NuGet\Install-Package Aicrosoft.Extensions.NLog -Version 8.0.0-beta.260130.2
                    
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="Aicrosoft.Extensions.NLog" Version="8.0.0-beta.260130.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Aicrosoft.Extensions.NLog" Version="8.0.0-beta.260130.2" />
                    
Directory.Packages.props
<PackageReference Include="Aicrosoft.Extensions.NLog" />
                    
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 Aicrosoft.Extensions.NLog --version 8.0.0-beta.260130.2
                    
#r "nuget: Aicrosoft.Extensions.NLog, 8.0.0-beta.260130.2"
                    
#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 Aicrosoft.Extensions.NLog@8.0.0-beta.260130.2
                    
#: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=Aicrosoft.Extensions.NLog&version=8.0.0-beta.260130.2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Aicrosoft.Extensions.NLog&version=8.0.0-beta.260130.2&prerelease
                    
Install as a Cake Tool

Aicrosoft.Extensions.NLog

Log-Related Extensions with NLog

Lastupdate: 2025-11-08 by Fisher

Using NLog

Use in Console Projects

Add the .AddNLog() at the entry point of the Program file.

 using IHost host = Host.CreateDefaultBuilder(args)
     .AddNLog()
     .Build()
     ;

Use in Web Projects

Add the .AddNLog() at the entry point of the Program file.

var builder = WebApplication.CreateBuilder(args);
builder.Host.AddNLog();

Modifying NLog's Variables

Place the code at the top, after LogHelper.GetCurrentClassLogger() is created.

#if !DEBUG
LogHelper.SetConfigurationVariable("logLevel", "Info");
#endif

It will modify the value of the variable logLevel configured in NLog to Info.


<variable name="logLevel" value="Trace" />

Injection Logger

Inject IServiceProvider to delay the instantiation of ILogger.

public abstract class ServiceBase(IServiceProvider serviceProvider)
{
    protected virtual IServiceProvider ServiceProvider { get; } = serviceProvider;

    private ILogger? logger;
    protected virtual ILogger Logger
    {
        get
        {
            logger ??= ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(GetType());
            return logger;
        }
    }
}

You can also inject ILogger through the constructor.

Creating a Logger Scope

Invoke within a extension BeginScopeLog in a method.

using var logDis = Logger.BeginScopeLog(out string scopedId);
  • The scopedId will be included in the log output and can also be used for business notes.
  • Before logDis is disposed, all log calls within the method include scopeId.

Output example:

2025-11-07 19:30:25.4782 [T][ 1|b75] StartupWatcher.ExecuteAsync_0 : StartupWatcher#Startup is finally  runContextJobs/totalContextJobs : 0/0]

The b75 in the log above is the first three characters of the scopedId.

Log Configuration

Below is a complete example of an NLog configuration.

nlog.config

<?xml version="1.0" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="./logs/nlogs.log"
>

	<variable name="logdir" value="./logs"/>
	<variable name="logLevel" value="Trace" />
	<variable name="logContext" value="[${uppercase:${level:truncate=1}}][${threadid:padding=2}|${lowercase:${scopeproperty:scopeId:truncate=3:padding=4}}]${event-properties:item=EventId_Id} ${callsite:includeNamespace=false:methodName=true}_${callsite-linenumber} : ${message} ${onexception:${newline}${exception:format=tostring}}"/>

	
	<extensions>
		<add assembly="Aicrosoft.Extensions.NLog" />
		<add assembly="NLog.MailKit"/>
	</extensions>

	
	<targets async="false">

		<default-target-parameters
			  type="File"
			  archiveAboveSize="104857600"
			  maxArchiveFiles="2"
			  maxArchiveDays="30"
			  keepFileOpen="false"
			  layout="${longdate} ${var:logContext}"/>

		
		<target name="console" xsi:type="ColoredConsole"
					layout="${date:format=HH\:mm\:ss\.ffff}:${var:logContext}">
			<highlight-row condition="level == LogLevel.Trace"  foregroundColor="DarkGray"/>
			<highlight-row condition="level == LogLevel.Debug"  foregroundColor="DarkCyan"/>
			<highlight-row condition="level == LogLevel.Info"  foregroundColor="White"/>
			<highlight-row condition="level == LogLevel.Warn"  foregroundColor="DarkYellow" />
			<highlight-row condition="level == LogLevel.Error"  foregroundColor="Red" />
			<highlight-row condition="level == LogLevel.Fatal"  foregroundColor="DarkRed" backgroundColor="Yellow"/>
		</target>

		
		<target name="runLog" xsi:type="File"
					fileName="${logdir}/${date:format=yyyy_MM_dd}.log"
             />

		
		<target name="errorLog" xsi:type="File"
					fileName="${logdir}/${date:format=yyyy_MM_dd}_ex.log"
           />

		
		<target name="asyncMail" xsi:type="AsyncWrapper" queueLimit="100" overflowAction="Discard">
			<target name="batchMail" xsi:type="BufferingWrapper" bufferSize="100" flushTimeout="1200000" slidingTimeout="true">
				<target name="mail" xsi:type="MailKit"
						smtpServer="smtp.163.com"
						smtpPort="465"
						enableSsl="true"
						smtpAuthentication="Basic"
						smtpUserName="aicrosoft@163.com"
						smtpPassword="KEbxQLqnydaWB7i8"
						from="aicrosoft@163.com"
						to="superJob@abcdeep.net"
						subject="JobAgent Warnning"
						body="${longdate} ${var:logContext} ${newline}${newline}"
				 />
			</target>
		</target>

	</targets>

	<rules>
		<logger name="*" minlevel="Trace" writeTo="console" />
		<logger name="*" minlevel="Warn" writeTo="asyncMail" />
		<logger name="*" minlevel="${var:logLevel}" writeTo="runLog" >
			<filters  defaultAction='log'>
				<when condition="starts-with('${logger}','Microsoft.')" action="Ignore" />
			</filters>
		</logger>
		<logger name="*" minlevel="error" writeTo="errorLog" />
	</rules>

</nlog>

NLog Extensions

NLog extension of azlevel

  • Formatted to support color and log level display in Azure Devops Pipelines.

NLog Configuration of azlevel

nlog.config

<?xml version="1.0" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="./logs/nlogs.log"
>
	<variable name="logdir" value="./logs"/>
	<variable name="logLevel" value="Trace" />
	<variable name="logContext" value="[${uppercase:${level:truncate=1}}][${threadid:padding=2}|${lowercase:${scopeproperty:scopeId:truncate=3:padding=4}}]${event-properties:item=EventId_Id} ${callsite:includeNamespace=false:methodName=true}: ${message} ${onexception:${newline}${exception:format=tostring}}" />

	<extensions>
		<add assembly="Aicrosoft.Extensions.NLog" />
	</extensions>

	
	<targets async="false">
		
		<default-target-parameters
				  type="File"
				  archiveAboveSize="104857600"
                maxArchiveFiles="2"
                maxArchiveDays="10"
				  keepFileOpen="false"
				  layout="${longdate} ${var:logContext}"/>

		
		<target name="pipeline" xsi:type="AzurePipelineConsole"
					layout="${azlevel}${message}${onexception:${newline}${exception:format=tostring}}">
		</target>
		
		<target name="pipelineLog" xsi:type="File"
				layout="${azlevel}${message}${onexception:${newline}${exception:format=tostring}}"
						fileName="${logdir}/az-${date:format=yyyy_MM_dd}.log"
             />

		<target name="runLog" xsi:type="File"
						fileName="${logdir}/${date:format=yyyy_MM_dd}.log"
             />

	</targets>

	<rules>
		<logger name="*" minlevel="${var:logLevel}" writeTo="pipeline" />
		<logger name="*" minlevel="${var:logLevel}" writeTo="pipelineLog" />
		<logger name="*" minlevel="${var:logLevel}" writeTo="runLog" >
			<filters  defaultAction='log'>
				
			</filters>
		</logger>
	</rules>
</nlog>
Product Compatible and additional computed target framework versions.
.NET 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Aicrosoft.Extensions.NLog:

Package Downloads
Aicrosoft.DataAccess.DbMigration

Extensions of Aicrosoft Ltd.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0-beta.260130.2 109 1/30/2026
8.0.0-beta.260127.1 105 1/27/2026
8.0.0-beta.251110.1 326 11/10/2025