AspNetCore 使用NLog日志,NLog是基于.NET平台开的类库!(又一神器)
NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。
NLog是一个简单灵活的.NET日志记录类库。通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。
NLog的API非常类似于log4net,且配置方式非常简单。NLog使用路由表(routing table)进行配置,但log4net却使用层次性的appender配置,这样就让NLog的配置文件非常容易阅读,并便于今后维护。
如何使用?
1.创建一个新的ASP.NET Core项目
2.添加项目依赖
- NLog.Web.AspNetCore
3.在项目目录下添加nlog.config文件:
<?xml version="1.0" encoding="utf-8" ?>
3.将nlog.config复制到bin文件夹
4.在startup.cs文件中添加
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;
using NLog.Extensions.Logging;
using NLog.Web;
namespace NlogDemo
{
public class Startup
{
public Startup(IConfiguration configuration,IHostingEnvironment env)
{
Configuration = configuration;
//配置nlog
env.ConfigureNLog("nlog.config");
}
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)
{
//把nlog添加到.net core
loggerFactory.AddNLog();
//add NLog.Web
app.AddNLogWeb();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
5.记录日志
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Index page says hello");
return View();
}
总结:
在我自己学习Nlog的时候,少了关键的一部那就是第三步,讲config输出到bin!!!