ASP.Net Logging Using NLog

1 篇文章 0 订阅
 My experience implementing logging on this site using NLog. It was very easy!

I should have been logging information and errors from day 1, but I guess its never too late to start. Based on Rob Conery's "endorsement", I chose to try NLog.

Step 1 was obviously to download the library. Then, I added the reference to NLog.dll in my web project and configured it. For configuration, NLog uses its own configuration file separate from Web.config and you don't have to do any modifications to Web.config at all. Below is my NLog.config, which is set up to log everything of level Info and above to the file specified (NLog.config goes in the root of the web app). As you can see, it is very straightforward to configure for your own needs:

 

<?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" >
  <targets>
    <target name="console" xsi:type="ColoredConsole"
      layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
    <target name="file" xsi:type="File" fileName="${basedir}/Logs/rrLog.log"
      layout="${date}: ${message}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="file" />
  </rules>
</nlog>


After this, all that is left is to actually put in your log statements. So for example, to log all unhandled exceptions in your ASP.Net application, put the following in Global.asax.cs:

protected void Application_Error() {
   Exception lastException = Server.GetLastError();
   NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
   logger.Fatal(lastException);
}

 

And that's it! It can't be any easier than that, so I am pretty happy with NLog right now. I might checkout Log4Net sometime to make a comparison, but I don't have any reason to do so at this point. BTW, I recommend creating your own Logger service that wraps NLog so that you can easily switch to a different library if needed. I'll be doing that right now.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值