Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NLogPublic

Getting started with ASP.NET Core 5

Rolf Kristensen edited this pageMay 31, 2025 ·24 revisions

⚠️ Missing the trace/debug logs?Check your appsettings.json


ℹ️ See alsoexample in GitHub


This tutorial is for ASP.NET Core 5.

0. Create a new ASP.NET Core project

In Visual Studio 2019. Version 16.8+ is needed

1. Add dependency in csproj manually or using NuGet

Install the latest:

in csproj:

<ItemGroup>  <PackageReferenceInclude="NLog.Web.AspNetCore"Version="4.*" />  <PackageReferenceInclude="NLog"Version="4.*" /></ItemGroup>

2. Create a nlog.config file.

Create nlog.config (lowercase all) file in the root of your project.

We use this example:

<?xml version="1.0" encoding="utf-8" ?><nlogxmlns="http://www.nlog-project.org/schemas/NLog.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd">      autoReload="true"      internalLogLevel="Info"      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt"><!-- enable asp.net core layout renderers-->  <extensions>    <addassembly="NLog.Web.AspNetCore"/>  </extensions><!-- the targets to write to-->  <targets><!-- File Target for all log messages with basic details-->    <targetxsi:type="File"name="allfile"fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" /><!-- File Target for own log messages with extra web details using some ASP.NET core renderers-->    <targetxsi:type="File"name="ownFile-web"fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /><!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection-->    <targetxsi:type="Console"name="lifetimeConsole"layout="${MicrosoftConsoleLayout}" />  </targets><!-- rules to map from logger name to target-->  <rules><!--All logs, including from Microsoft-->    <loggername="*"minlevel="Trace"writeTo="allfile" /><!--Output hosting lifetime messages to console target for faster startup detection-->    <loggername="Microsoft.Hosting.Lifetime"minlevel="Info"writeTo="lifetimeConsole, ownFile-web"final="true" /><!--Skip non-critical Microsoft logs and so log only own logs (BlackHole)-->    <loggername="Microsoft.*"maxlevel="Info"final="true" />    <loggername="System.Net.Http.*"maxlevel="Info"final="true" />        <loggername="*"minlevel="Trace"writeTo="ownFile-web" />  </rules></nlog>

More details of the config file arehere.

Notice that one might have to pay special attention to theHosting Lifetime Startup Messages, if removing all other LoggingProviders (Like Console) and only using NLog. As it can cause hosting environment (Visual Studio / Docker / Azure Container) to not see application as started.

3. Update program.cs

Update the program.cs to includeUseNLog():

usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Hosting;usingMicrosoft.Extensions.Logging;usingSystem;usingNLog.Web;namespaceASP.NET_Core_5_NLog_Example{publicclassProgram{publicstaticvoidMain(string[]args){// Early init of NLog to allow startup and exception logging, before host is builtvarlogger=NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();try{logger.Debug("init main");CreateHostBuilder(args).Build().Run();}catch(Exceptionexception){//NLog: catch setup errorslogger.Error(exception,"Stopped program because of exception");throw;}finally{// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)NLog.LogManager.Shutdown();}}publicstaticIHostBuilderCreateHostBuilder(string[]args)=>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder=>{webBuilder.UseStartup<Startup>();}).ConfigureLogging(logging=>{logging.ClearProviders();logging.SetMinimumLevel(LogLevel.Trace);}).UseNLog();// NLog: Setup NLog for Dependency injection}}

4. Configure appsettings.json

The Logging configuration specified inappsettings.json overrides any call toSetMinimumLevel. So either remove"Default": or adjust it correctly to your needs.

{"Logging": {"LogLevel": {"Default":"Trace","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"    }  },"AllowedHosts":"*"}

Remember to also update any environment specific configuration to avoid any surprises. Exappsettings.Development.json

5. Write logs

Inject the ILogger in your controller:

usingMicrosoft.Extensions.Logging;publicclassHomeController:Controller{privatereadonlyILogger<HomeController>_logger;publicHomeController(ILogger<HomeController>logger){_logger=logger;_logger.LogDebug(1,"NLog injected into HomeController");}publicIActionResultIndex(){_logger.LogInformation("Hello, this is the index!");returnView();}

6. Example Output

When starting the ASP.NET Core website, we get two files:

nlog-own-2020-12-29.log

2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main |url: |action: 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index

nlog-all-2020-12-29.log

2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 5\ASP.NET Core 5 NLog Example 2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController 2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index!

Configure NLog Targets for output

Next step, seeConfigure NLog with nlog.config

-Troubleshooting Guide - See available NLog Targets and Layouts:https://nlog-project.org/config

Configuration

Programmatic Configuration

Advanced

Extending NLog

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp