1. Add dependency in csproj manually or using NuGet

Install the latest:

  • NLog.Web.AspNetCore 4.5+
  • Update the NLog package if possible

in csproj:

<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.1" />
<PackageReference Include="NLog" Version="4.5.1" />

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" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="c:\temp\internal-nlog.txt"> <!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions> <!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets> <!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>

More details of the config file are here.

If you like to include other targets or layout renderers, check the Platform support table, as there is a limited set implemented. Check the column NetStandard. To read more about NetStandard, see the docs from Microsoft

3. Enable copy to bin folder

Enable copy to bin folder for nlog.config

or edit .csproj file manually and add:

  <ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

4. Update program.cs

Update the program.cs

add using NLog.Web; and using Microsoft.Extensions.Logging;

 public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
BuildWebHost(args).Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "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();
}
} public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog() // NLog: setup NLog for Dependency injection
.Build();

5. Configure appsettings.json

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

 {
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
}
}

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

6. Write logs

Inject the ILogger in your controller:


 using Microsoft.Extensions.Logging;

 public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
} public IActionResult Index()
{
_logger.LogInformation("Index page says hello");
return View();
}


7. Example Output

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

nlog-own-2017-10-10.log

2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main |url: |action:
2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index! |url: http://localhost/|action: Index

nlog-all-2017-10-10.log

2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main
2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\j.verdurmen\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
2017-10-10 23:40:30.9897|37|DEBUG|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Reading data from file 'C:\Users\j.verdurmen\AppData\Local\ASP.NET\DataProtection-Keys\key-bfd1ce07-8dc6-4eef-a51a-d21ddb547109.xml'.
2017-10-10 23:40:31.0004|18|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Found key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109}.
2017-10-10 23:40:31.0124|13|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Considering key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} with expiration date 2017-12-28 19:01:07Z as default key.
2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60
2017-10-10 23:40:31.0422|51|DEBUG|Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor|Decrypting secret element using Windows DPAPI.
2017-10-10 23:40:31.0422|0|DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60
2017-10-10 23:40:31.0422|4|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC.
2017-10-10 23:40:31.0543|3|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory|Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC.
2017-10-10 23:40:31.0543|2|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Using key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} as the default key.
2017-10-10 23:40:31.0543|0|DEBUG|Microsoft.AspNetCore.DataProtection.Internal.DataProtectionStartupFilter|Key ring with default key {bfd1ce07-8dc6-4eef-a51a-d21ddb547109} was loaded during application startup.
2017-10-10 23:40:31.4080|3|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting starting
2017-10-10 23:40:31.5508|4|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Hosting started
2017-10-10 23:40:31.5508|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly ASP.NET Core 2 - VS2017
2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.ApplicationInsights.HostingStartup
2017-10-10 23:40:31.5526|0|DEBUG|Microsoft.AspNetCore.Hosting.Internal.WebHost|Loaded hosting startup assembly Microsoft.AspNetCore.Server.IISIntegration
2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK64" started.
2017-10-10 23:40:31.6909|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" started.
2017-10-10 23:40:31.7418|19|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK65" reset.
2017-10-10 23:40:31.7418|10|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" disconnecting.
2017-10-10 23:40:31.7418|7|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv|Connection id "0HL8G4U42CK65" sending FIN.
2017-10-10 23:40:31.7591|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HL8G4U42CK65" stopped.
2017-10-10 23:40:31.8153|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:56152/
2017-10-10 23:40:31.8607|4|DEBUG|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|The request path / does not match a supported file type
2017-10-10 23:40:32.0160|1|DEBUG|Microsoft.AspNetCore.Routing.RouteBase|Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
2017-10-10 23:40:32.1120|1|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017)
2017-10-10 23:40:32.1326|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017) with arguments ((null)) - ModelState is Valid
2017-10-10 23:40:32.1326|0|INFO|ASP.NET_Core_2___VS2017.Controllers.HomeController|Hello, this is the index!
2017-10-10 23:40:32.1620|2|DEBUG|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action method ASP.NET_Core_2___VS2017.Controllers.HomeController.Index (ASP.NET Core 2 - VS2017), returned result Microsoft.AspNetCore.Mvc.ViewResult.
2017-10-10 23:40:32.1620|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine|View lookup cache miss for view 'Index' in controller 'Home'.
2017-10-10 23:40:33.6906|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Home\Index.cshtml' started.
2017-10-10 23:40:35.7180|2|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\Home\Index.cshtml' completed in 2024.1338ms.
2017-10-10 23:40:35.7988|1|DEBUG|Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler|Compilation of the generated code for the Razor file at 'X:\nlog\NLog.Web\examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\Views\_ViewStart.cshtml' started.

How to use Nlog for ASP.NET Core with csproj的更多相关文章

  1. Elasticsearch,Kibana,Logstash,NLog实现ASP.NET Core 分布式日志系统

    Elasticsearch - 简介 Elasticsearch 作为核心的部分,是一个具有强大索引功能的文档存储库,并且可以通过 REST API 来搜索数据.它使用 Java 编写,基于 Apac ...

  2. 使用 NLog 给 Asp.Net Core 做请求监控

    为了减少由于单个请求挂掉而拖垮整站的情况发生,给所有请求做统计是一个不错的解决方法,通过观察哪些请求的耗时比较长,我们就可以找到对应的接口.代码.数据表,做有针对性的优化可以提高效率.在 asp.ne ...

  3. [转]Using NLog for ASP.NET Core to write custom information to the database

    本文转自:https://github.com/NLog/NLog/issues/1366 In the previous versions of NLog it was easily possibl ...

  4. NLog在asp.net core中的应用

    Asp.net core中,自带的Log是在当selfhost运行时,在控制台中输出,不便于查阅,如果用一个log架框,把日志持久化,便于查询. NLog是一个免费的日志记录框架,专门为.net平台下 ...

  5. [转]ASP.NET Core 开发-Logging 使用NLog 写日志文件

    本文转自:http://www.cnblogs.com/Leo_wl/p/5561812.html ASP.NET Core 开发-Logging 使用NLog 写日志文件. NLog 可以适用于 . ...

  6. ASP.NET Core 开发-Logging 使用NLog 写日志文件

    ASP.NET Core 开发-Logging 使用NLog 写日志文件. NLog 可以适用于 .NET Core 和 ASP.NET Core . ASP.NET Core已经内置了日志支持,可以 ...

  7. ASP.NET Core 实战:使用 NLog 将日志信息记录到 MongoDB

    一.前言 在项目开发中,日志系统是系统的一个重要组成模块,通过在程序中记录运行日志.错误日志,可以让我们对于系统的运行情况做到很好的掌控.同时,收集日志不仅仅可以用于诊断排查错误,由于日志同样也是大量 ...

  8. ASP.NET Core 添加NLog日志支持(VS2015update3&VS2017)

    1.创建一个新的ASP.NET Core项目 2.添加项目依赖 NLog.Web.AspNetCore 3.在项目目录下添加nlog.config文件: <?xml version=" ...

  9. ASP.NET Core使用NLog记录日志

    1.根目录新建nlog.config配置文件 <?xml version="1.0"?> <nlog xmlns="http://www.nlog-pr ...

随机推荐

  1. iOS - 断言处理与调试

    一.Objective - C 中的断言: Objective - C 中的断言处理使用的是 NSAssertionHandler : 每个线程拥有它自己的断言处理器,它是 NSAssertionHa ...

  2. Web基础之http协议

    第6章 Web基础之http协议 第6章 Web基础之http协议一.http协议介绍 1.1)什么是超文本 1.2)什么是URL 1.3)什么是超文本传输协议二.访问网站分析三.页面请求信息解析(仅 ...

  3. CQRS架构下的Saga流程重构

  4. Ubuntu安装SFTP服务,及启动失败处理

    安装openssh-server sudo apt-get install openssh-server 查看是否安装成功 dpkg --get-selections | grep ssh 新建用户组 ...

  5. bzoj4530 [Bjoi2014]大融合 子树信息 LCT

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=4530/ 题解 想要求出一条边的负载那么就是要求出一个点为根的时候的另一个点的子树大小. 又因为 ...

  6. python碎片 - 函数参数

    一个*传参: 方式1:如果想传一个列表中的值,实参前加*.如: *[1,2,3] 方式2:直接传入一个列表,不加*.如[1,2,3],则传入的是一整个列表,包括[] 两个**传参: 方式1,:{nam ...

  7. java:集合输出之Iterator和ListIterator二

    java:集合输出之Iterator和ListIterator二 ListIterator是Iterator的子接口,Iterator的最大特点是,能向前,或向后迭代.如果现在要想双向输出的话,则只能 ...

  8. 【NOIP2015模拟10.22】最小代价

    前言 本来在比赛上就想到最小生成树了,但不相信这道题那么简单,然后就没有然后了... 题目 给出一幅由n个点m条边构成的无向带权图. 其中有些点是黑点,其他点是白点. 现在每个白点都要与他距离最近的黑 ...

  9. Vue-Awesome-Swiper实现缩略图控制循环,循环背景图,显示多图轮播,点击左右滚动一张图

    效果图: 本姐只展示关键代码哈 上代码:网站有完整代码,但是数据不是循环的.https://surmon-china.github.io/vue-awesome-swiper/ 循环数据的代码在此: ...

  10. 如何生成各种mif文件,绝对经典!!!

    mif文件生成模板,只需要5步,很简单!!!!! 先说明如何操作,1-2-3-4-5步,后面附上模板!!! 下面以汉字去模演示过程: 1.取模软件设置:注意这里是设置的输出数据的格式!!!!!!!!! ...