1. 新建netcore2.0项目
2.右键 “依赖项” -> “管理NuGet程序包...”
搜索NLog.Web.AspNetCore,版本为v4.5.0-rc2 并安装。
新建一个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: empinternal-nlog.txt"> <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="c: emp log-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: emp log-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger}|${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> <!-- 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. 修改文件属性
复制到输出目录->始终复制
4.在HomeController添加如下代码:
private ILogger<HomeController> logger; public HomeController(ILogger<HomeController> _logger) { logger = _logger; }
5. 在使用的地方调用logger.LogXXX("Hello,Index");即可输出日志。