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 more

Other 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

ASP.NET MVC 与NLog的使用的更多相关文章

  1. .net framework 4.6 asp.net mvc 使用NLog

    NUGET添加NLog和NLog.Config的引用 配置NLog.config <?xml version="1.0" encoding="utf-8" ...

  2. NLog在Asp.Net MVC的实战应用

    Asp.Net MVC FilterAttribute特性.读取xml反序列化.NLog实战系列文章 首先新建一个MVC project. 一.NLog的配置. 作者:Jarosław Kowalsk ...

  3. EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象

    EF+LINQ事物处理   在使用EF的情况下,怎么进行事务的处理,来减少数据操作时的失误,比如重复插入数据等等这些问题,这都是经常会遇到的一些问题 但是如果是我有多个站点,然后存在同类型的角色去操作 ...

  4. 17+个ASP.NET MVC扩展点【附源码】

    1.自定义一个HttpModule,并将其中的方法添加到HttpApplication相应的事件中!即:创建一个实现了IHttpmodule接口的类,并将配置WebConfig.  在自定义的Http ...

  5. 17+个ASP.NET MVC扩展点,含源码{转}

    1.自定义一个HttpModule,并将其中的方法添加到HttpApplication相应的事件中!即:创建一个实现了IHttpmodule接口的类,并将配置WebConfig.在自定义的HttpMo ...

  6. asp.net mvc ,asp.net mvc api 中使用全局过滤器进行异常捕获记录

    MVC下的全局异常过滤器注册方式如下:标红为asp.net mvc ,asp.net mvc api  注册全局异常过滤器的不同之处 using SuperManCore; using System. ...

  7. ASP.NET MVC扩展点

    16个ASP.NET MVC扩展点[附源码] 1.自定义一个HttpModule,并将其中的方法添加到HttpApplication相应的事件中!即:创建一个实现了IHttpmodule接口的类,并将 ...

  8. ASP.NET MVC 常用扩展点:过滤器、模型绑定等

    一.过滤器(Filter) ASP.NET MVC中的每一个请求,都会分配给对应Controller(以下简称“控制器”)下的特定Action(以下简称“方法”)处理,正常情况下直接在方法里写代码就可 ...

  9. 整理学习ASP.NET MVC的资源

    网站 http://www.asp.net/mvc http://stackoverflow.com/questions/tagged/asp.net-mvc+asp.net-mvc-4?sort=n ...

随机推荐

  1. 学python之路前的一些话

    为什么学python: 这些年一直从事运维相关的工作.但做下来感觉都是些很基础的东西,无非就是对一些命令或者问题处理很熟练而已,混的都是经验.曾很羡慕会写shell脚本,会自动化安装程序的运维组组长, ...

  2. tp5 excel导出类

    1.引入Loader use think\Loader; 2.导出方法: /** * excel表格导出 * @param string $fileName 文件名称 * @param array $ ...

  3. C#-VS异常处理

    VS异常处理 常规 try     可能会产生异常的代码,当一行产生异常,这行下面的代码不执行,转到catch开始执行 catch(system.Exception e)      e.message ...

  4. web-day10

    第10章WEB10-requet&response篇 今日任务 登录系统后完成文件下载 商城系统注册功能. 教学导航 教学目标 掌握response设置响应头 掌握response重定向和转发 ...

  5. LCA的 RMQ解法模版

    struct Edge{ int from, to, nex; }edge[N<<1]; int head[N], edgenum; void addedge(int u, int v){ ...

  6. [mobile]监听手机mobile上面软键盘的回车[enter]事件

    $(document).keypress(function(e) { if(e.which == 13) { if(!$(".qaSearchInput").val()) { Hn ...

  7. Android-Java-单例模式优化&多线程并发

    上一篇博客,Android-Java单例模式,介绍了在真实开发过程中,普遍使用的几种单例模式,而今天这篇博客,将要对单利模式进行优化 并且 通过多线程并发来分析 单利模式的优化: 对于为什么会出现安全 ...

  8. [leetcode 120]triangle 空间O(n)算法

    1 题目 Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjac ...

  9. cad.net的undo返回操作

    这是提供给许多从lisp转移到c#的开发人员的一个函数,这个函数利用后绑代码实现undo返回操作. 本代码由edata提供: edata博客 /// <summary> /// 命令动作编 ...

  10. 详述MSSQL服务在渗透测试中的利用(上篇)

    前言: 致力于复现最实用的漏洞利用过程. 本文将带领大家学习以下内容: 学习使用`xp_cmdshell`扩展存储过程 学习调用`wscript.shell` 学习MSSQL写文件 学习沙盘模式提权 ...