您的位置:首页 > 编程语言 > ASP

ASP.NET Core 2.0系列学习笔记-NLog日志配置文件

2018-02-27 20:49 726 查看
一、新建ASP.NET Core 2.0 MVC项目,使用NuGet在浏览中搜索:NLog.Web.AspNetCore,如下图所示:



二、在项目的bin\Debug\netcoreapp2.0\下新建一个xml类型的nlog.config文件,如下图(结合上图观看):



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="Warn"
internalLogFile="internal-nlog.txt">

<!--define various log targets-->
<targets>

<!--write logs to file-->
<target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

<target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

<target xsi:type="Null" name="blackhole" />

</targets>

<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>三、在Startup类中添加配置,修改代码如下所示:using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; //ILoggerFactory
using NLog.Extensions.Logging; //ConfigureNLog
using NLog.Web; //AddNLogWeb

namespace NETCoreNLog
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

// 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)
{

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

loggerFactory.AddNLog(); //添加NLog
app.AddNLogWeb();
loggerFactory.ConfigureNLog("nlog.config");//读取Nlog配置文件

app.UseStaticFiles(); //注册wwwroot静态文件

//注册MVC路由
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

注:文件头先引用 using Microsoft.Extensions.Logging;using NLog.Extensions.Logging;和using NLog.Web;
四、使用NLog日志:
1.在Main方法中调用ConfigAndLog();public static IConfigurationRoot Configuration { get; set; } //读取指定json配置文件
public static Logger nlog = LogManager.GetCurrentClassLogger(); //获得日志实例
public static void ConfigAndLog()
{
     var builder = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json");
     Configuration = builder.Build();
     string app_key = Configuration["appSettings:app_key"]; 
     string conn = Configuration["connectionStrings:conn"]; //读取数据库连接字符串
     nlog.Debug($"数据库连接为:{conn}"); //Nlog日志使用   
}
public static void Main(string[] args)
{
BuildWebHost(args).Run();
ConfigAndLog();
}
2.在控制器IActionResult中使用Nlog//获得日志的实例
public static Logger nlog = LogManager.GetCurrentClassLogger();
public IActionResult Index()
{
nlog.Info("普通信息日志-----------");
nlog.Debug("调试日志-----------");
nlog.Error("错误日志-----------");
nlog.Fatal("异常日志-----------");
nlog.Warn("警告日志-----------");
nlog.Trace("跟踪日志-----------");
nlog.Log(LogLevel.Warn, "Log日志------------------");
return View();
}注:NLog日志的位置默认是在bin\Debug下面。
参考:http://www.voidcn.com/article/p-hukbuiwx-bch.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息