上一篇简单介绍了日志的使用方法,也仅仅是用来做下学习,更何况只能在console输出。
NLog已是日志库的一员大佬,使用也简单方便,本文介绍的环境是居于.NET CORE 2.0 ,目前的版本也只有beta版。
一、安装和配置
1.安装
命令如下
PM> Install-Package NLog.Web.AspNetCore -Version 4.5.0-beta04
2.创建配置文件
在web项目根目录下,创建配置文件nlog.config ,并且将文件的属性“复制到输出目录”设置为"始终复制"。
示例如下:
<?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">
<!-- 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}" />
<!-- 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}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<!-- write to the void aka just remove -->
<target xsi:type="Null" name="blackhole" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
3.初始化
更新program.cs,添加引用
using NLog.Web;
修改代码
public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
BuildWebHost(args).Run();
}
catch (Exception e)
{
//NLog: catch setup errors
logger.Error(e, "Stopped program because of exception");
throw;
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog() // NLog: setup NLog for Dependency injection
.Build();
二、使用
配置好了之后,将ILogger注入到控制器就可以写日志了。
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();
}
}
三、日志输出
访问刚才的index就可以在日志目录下看到2个生成的文件了。
nlog-all-2017-11-18.log
2017-11-18 23:09:02.2839||DEBUG|Tkx.Web.Program|init main
2017-11-18 23:09:02.6079||INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using ‘C:\Users\Administrator\AppData\Local\ASP.NET\DataProtection-Keys‘ as key repository and Windows DPAPI to encrypt keys at rest.
2017-11-18 23:09:03.0070||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 POST http://localhost:59491/account/login application/x-www-form-urlencoded 26
2017-11-18 23:09:03.0320||INFO|Microsoft.AspNetCore.Cors.Infrastructure.CorsService|Policy execution successful.
2017-11-18 23:09:03.1720||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method Tkx.Web.Controllers.AccountController.Login (Tkx.Web) with arguments (Tkx.WebApi.Models.User.UserLogin) - ModelState is Valid
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123
2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================
2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123
2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1
2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService:
2017-11-18 23:09:03.3500||INFO|Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor|Executing JsonResult, writing value Tkx.Web.ResponseMessage.
2017-11-18 23:09:03.5290||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action Tkx.Web.Controllers.AccountController.Login (Tkx.Web) in 398.631ms
2017-11-18 23:09:03.5440||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 543.2871ms 200 application/json; charset=utf-8
nlog-own-2017-11-18.log
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1 |url: http://localhost/account/login|action: login
2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService: |url: http://localhost/account/login|action: login
在业务层使用方法一样简单,只要在业务层引入该库就可以。 如日志所显示的UserService就是我的业务层。 写到最后,说一句,其实就是翻译了官网的文档而已
相关文档
项目地址:https://github.com/NLog/NLog.Web nlog使用方法
https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
配置文件的详细使用说明
https://github.com/NLog/NLog/wiki/Configuration-file
时间: 2024-10-10 04:52:22