asp.net core项目添加NLog
用VS2017新增一个.net core项目。
通过Nuget安装:NLog.Web.AspNetCore
1.在项目中添加 NLog.config文件

2.配置文件中添加如下代码(摘录官方文档):
<?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="Warn" internalLogFile="c:\temp\internal-nlog.txt"> <!-- Load the ASP.NET Core plugin --> <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}|${logger}|${uppercase:${level}}|${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}|${logger}|${uppercase:${level}}| ${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>
在target中:通过filename指定文件的名称(输出路径),layout指定输出的内容格式。
action: ${aspnet-mvc-action}记录action中记录的日志。
在logger中:minlevel指定文件记录的最低级别的日志,workto表明是哪个文件
3.startup.cs文件做如下修改
using NLog.Extensions.Logging; using NLog.Web; public Startup(IHostingEnvironment env) { env.ConfigureNLog("nlog.config"); } public void ConfigureServices(IServiceCollection Services) { //call this in case you need aspnet-user-authtype/aspnet-user-identity services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //add NLog to ASP.NET Core loggerFactory.AddNLog(); //add NLog.Web app.AddNLogWeb();
}
4.控制器中添加测试代码

官方文档:
浙公网安备 33010602011771号