NLog是一個.NET 下一個完善的日志工具,個人已經在項目中使用很久,與ELMAH相比,可能EAMAH更側重 APS.NET MVC 包括調試路由,性能等方面,而NLog則更簡潔。
github: https://github.com/NLog/NLog
web: http://nlog-project.org
logview:http://www.gibraltarsoftware.com/loupe/extensions/nlog
http://stackoverflow.com/questions/710863/log4net-vs-nlog
http://stackoverflow.com/questions/4091606/most-useful-nlog-configurations
Supported targets include:
Files - single file or multiple, with automatic file naming and archival
Event Log - local or remote
Database - store your logs in databases supported by .NET
Network - using TCP, UDP, SOAP, MSMQ protocols
Command-line console - including color coding of messages
E-mail - you can receive emails whenever application errors occur
ASP.NET trace
... and many moreOther key features:
very easy to configure, both through configuration file and programmatically
easy-to-use logger pattern known from log4xxx
advanced routing using buffering, asynchronous logging, load balancing, failover, and more
cross-platform support: .NET Framework, .NET Compact Framework and Mono (on Windows and Unix)
安裝
配置
<?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"> <!-- See http://nlog-project.org/wiki/Configuration_file for information on customizing logging rules and outputs. --> <!-- 使用說明 1.一般控制台調式日志(打印到控制台) logger.Trace("GetHotelBrand 操作數據庫異常 sqlText : " + sqlText); 2. 一般文本日志,如記錄接口,響應值等 請求參數等(記錄文本,支持異步), logger.Info("GetHotelBrand 操作數據庫異常 sqlText : " + sqlText); 3.錯誤日志 一般影響到業務流程的正常使用 (記錄到DB) logger.ErrorException("GetHotelBrand 操作數據庫異常 sqlText : " + sqlText, ex); 4.致命性錯誤 如金額數據,訂單數據操作失敗 (發送郵件通知) logger.FatalException("GetHotelBrand 操作數據庫異常 sqlText : " + sqlText, ex); --> <targets> <!-- add your targets here --> <!--調式打印控制台日志--> <target name="console" xsi:type="ColoredConsole" layout="[${date:format=yyyy-MM-dd HH\:mm\:ss}][${level}] ${message} ${exception}"/> <!-- 記錄一般INFO文本日志(啟用異步) --> <target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard"> <target xsi:type="File" fileName="${basedir}/logs/${shortdate}/${level}.log" layout="${longdate} ${uppercase:${level}} ${message}" maxArchiveFiles="100" /> </target> <!-- 發生錯誤異常記錄數據庫日志 --> <target name="database" xsi:type="Database" useTransactions="true" connectionString="Data Source=xxxxxxxx;Initial Catalog=Log;Persist Security Info=True;User ID=sa;Password=123456" commandText="insert into NLogException_HomeinnsInterface([CreateOn],[Origin],[LogLevel], [Message], [Exception],[StackTrace]) values (getdate(), @origin, @logLevel, @message,@exception, @stackTrace);"> <!--日志來源--> <parameter name="@origin" layout="${callsite}"/> <!--日志等級--> <parameter name="@logLevel" layout="${level}"/> <!--日志消息--> <parameter name="@message" layout="${message}"/> <!--異常信息--> <parameter name="@exception" layout="${exception}" /> <!--堆棧信息--> <parameter name="@stackTrace" layout="${stacktrace}"/> </target> <!-- 發生致命錯誤發送郵件日志 --> <target name="email" xsi:type="Mail" header="-----header------" footer="-----footer-----" layout="${longdate} ${level} ${callsite} ${message} ${exception:format=Message, Type, ShortType, ToString, Method, StackTrace}" html="false" encoding="UTF-8" addNewLines="true" subject="${message}" to="" from="" body="${longdate} ${level} ${callsite} ${message} ${exception:format=Message, Type, ShortType, ToString, Method, StackTrace}" smtpUserName="" enableSsl="false" smtpPassword="" smtpAuthentication="Basic" smtpServer="smtp.163.com" smtpPort="25"> </target> </targets> <rules> <!-- add your logging rules here --> <logger name="*" minlevel="Trace" writeTo="console" /> <logger name="*" minlevel="Info" writeTo="file" /> <logger name="*" minlevel="Error" writeTo="database"/> <logger name="*" minlevel="Fatal" writeTo="email" /> </rules> </nlog>
配置什么的也沒有什么好說的,跟相對Log4j配置簡潔些,支持 控制台,文件(異步),數據庫,Email,夠用了,其他的方式還沒有研究。
日志查看
這里推薦一款日志查看工具:Loupe ,支持.NET 平台下集成,在Asp.NET MVC 下只需要配置Nuget引用相應的包。
Install-Package Gibraltar.Agent.Web.Mvc
注冊攔截器
using Gibraltar.Agent; using Gibraltar.Agent.Web.Mvc.Filters; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { // Initialize Gibraltar Loupe Log.StartSession(); GlobalConfiguration.Configuration.Filters.Add(new WebApiRequestMonitorAttribute()); GlobalFilters.Filters.Add(new MvcRequestMonitorAttribute()); GlobalFilters.Filters.Add(new UnhandledExceptionAttribute()); } }
結合SignalR
今天看到一篇與signalr結合的文章,可以把記錄的日志主動推送到瀏覽器 : http://www.codeproject.com/Articles/758633/Streaming-logs-with-SignalR ,原理NLog支持MethodCallTarget特性,發生異常時,可以觸發Signalr的相關方法,從而推送錯誤消息到瀏覽器。
<configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" /> </configSections> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="false"> <targets> <target name="debug" xsi:type="Debugger" layout=" #${longdate} - ${level} - ${callsite} - ${message}" /> <target name="signalr" xsi:type="MethodCall" className="SignalRTargetHub, App_Code" methodName="Send"> <parameter layout="${longdate}" /> <parameter layout="${level}" /> <parameter layout="${callsite}: ${message}" /> </target> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="debug" /> <logger name="*" minlevel="Trace" writeTo="signalr" /> </rules> </nlog>
使用OWIN宿主,Open Web Interface for .NET (OWIN)在Web服務器和Web應用程序之間建立一個抽象層。OWIN將網頁應用程序從網頁服務器分離出來,然后將應用程序托管於OWIN的程序而離開IIS之外。
public class SignalRTargetHub : Hub { public void Hello() { this.Clients.Caller.logEvent( DateTime.UtcNow.ToLongTimeString(), "info", "SignalR connected"); } static IHubContext signalRHub; public static void Send(string longdate, string logLevel, String message) { if (signalRHub == null) { signalRHub = GlobalHost.ConnectionManager.GetHubContext<SignalRTargetHub>(); } if (signalRHub != null) { signalRHub.Clients.All.logEvent(longdate, logLevel, message); } } } [assembly: OwinStartup(typeof(SignalRStartup))] public class SignalRStartup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } }
注冊Global事件
Logger logger = NLog.LogManager.GetCurrentClassLogger(); void Application_Error(object sender, EventArgs e) { Exception lastException = Server.GetLastError(); logger.Fatal("Request: '{0}'\n Exception:{1}", HttpContext.Current.Request.Url, lastException); }
Refer:
How to NLog (2.1) with VisualStudio 2013
http://www.codeproject.com/Tips/749612/How-to-NLog-with-VisualStudio
Logging: How to Growl with NLog 3
http://www.codeproject.com/Articles/786304/Logging-How-to-Growl-with-NLog-or
Five methods to Logging in MVC 3.0(介紹較詳細,需翻牆)
http://www.codeproject.com/Tips/237171/Five-methods-to-Logging-in-MVC
微軟最新的Web服務器Katana發布了版本3(OWIN)
http://www.infoq.com/cn/news/2014/08/Katana-3