NLog在asp.net core中的应用

  Asp.net core中,自带的Log是在当selfhost运行时,在控制台中输出,不便于查阅,如果用一个log架框,把日志持久化,便于查询.

  NLog是一个免费的日志记录框架,专门为.net平台下的框架提供日志功能,本文主要说明asp.net core下怎么使用NLog。

  首先用Nuget安装NLog.Extensions.Logging和NLog.Web.AspNetCore两个类库。

  修改project.json,在publishOptions中添加”nlog.config节点”

  "publishOptions": {

  "include": [

  "wwwroot",

  "**/*.cshtml",

  "appsettings.json",

  "web.config",

  "nlog.config"

  ]

  }

  在StartUp.cs中添加

  public void ConfigureServices(IServiceCollection services)

  {

  // Add framework services.

  services.AddMvc();

  //为NLog.web注入HttpContextAccessor

  services.AddSingleton();

  ……

  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

  {

  //添加NLog到.net core框架中

  loggerFactory.AddNLog();

  //添加NLog的中间件

  app.AddNLogWeb();

  //指定NLog的配置文件

  env.ConfigureNLog("nlog.config");

  ……

  }

  HomeController.cs中是自定义日志

  static Logger Logger = LogManager.GetCurrentClassLogger();

  public IActionResult Index()

  {

  Logger.Info("普通信息日志");

  Logger.Debug("调试日志");

  Logger.Error("错误日志");

  Logger.Fatal("异常日志");

  Logger.Warn("警告日志");

  Logger.Trace("跟踪日志");

  Logger.Log(NLog.LogLevel.Warn, "Log日志");

  try

  {

  int i = 0;

  var a = 10 / i;

  }

  catch (Exception exc)

  {

  //异常日志

  Logger.Fatal(exc, exc.Message);

  }

  return View();

  }

  NLog.config,有两种日志,记录在C:\temp下,一种是全部日志,一种是自己通过NLog函数记录的日志。如果日志库异常,会产生在c:\temp\internal-nlog.txt下,

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  autoReload="true"

  internalLogLevel="Warn"

  internalLogFile="c:\temp\internal-nlog.txt">

  layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

  layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

  Layout中$后的数据就是要写日志的内容,可以根据自己的需要,选择要保存的日志数据.

  如果想把日志保存到数据库中,可以把NLog.config修改如下:

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  autoReload="true"

  internalLogLevel="Warn"

  internalLogFile="c:\temp\internal-nlog.txt">

  INSERT INTO [dbo].[NLog] (

  [MachineName],

  [SiteName],

  [Logged],

  [Level],无锡好的男科医院 http://www.zzchnk.com/

  [UserName],

  [Message],

  [Logger],

  [Properties],

  [Host],

  [Controller],

  [Action],

  [Url],

  [CallSite],

  [Exception]

  ) VALUES (

  @machineName,

  @siteName,

  @logged,

  @level,

  @userName,

  @message,

  @logger,

  @properties,

  @host,

  @controller,

  @action,

  @url,

  @callSite,

  @exception

  );

猜你喜欢

转载自www.cnblogs.com/djw12333/p/10937420.html