NLog的安装请百度,我安装的是3.2。NLog可以向文件,数据库,邮件等写日志,想了解请百度,这里讲怎么写入数据库,及常常会遇到的问题:
1、layout render
NLog内置了很多日志内容格式,样子就是${longdate}之类的,详见:https://github.com/NLog/NLog/wiki/Layout-Renderers
2、如果我们要自定义日志:
<target xsi:type="Database" name="LogOnlog" connectionStringName ="DataBase" > <commandText> Insert into MyLog(Operator_name,Operator_Type,IP,DateTime,Operation) Values(@Operator_name,@Operator_Type,@IP,@DateTime,@Operation); </commandText> <parameter name = "@Operator_name" layout = "${event-context:item=Operator_name}"/> <parameter name = "@Operator_Type" layout = "${event-context:item=Operator_Type}" /> <parameter name = "@DateTime" layout = "${event-context:item=DateTime}"/> <parameter name = "@IP" layout = "${event-context:item=IP}" /> <parameter name = "@Operation" layout = "${event-context:item=Operation}" /> </target> </targets> <rules> <logger name="*" minlevel="Trace " writeTo="LogOnlog"/> </rules>
${event-context:item=Operation}中:后面的“Operation”在生成Logger时会形成名为“Operation”的键,我们就可以在代码中对他赋值,详见:https://github.com/NLog/NLog/wiki/EventContext-Layout-Renderer。我代码中是这样:
Logger logger = LogManager.GetCurrentClassLogger(); //不能用 Logger logger =new Logger();,会报错:“NLog.Logger.Logger()”不可访问,因为它受保护级别限制
LogEventInfo lei = new LogEventInfo();
lei.Properties["Operator_name"] = Opeator_Name;
lei.Properties["Operator_Type"] = Operator_Type;
lei.Properties["DateTime"] = DateTime.Now;
lei.Properties["IP"] = GetClientIPOrAdd.GetIP();
lei.Properties["Operation"] = Operation;
lei.Level = LogLevel.Info;
logger.Log(lei);
3、要点:当我们修改 NLog.config 文件时,要重新编译解决方案,修改才会起作用。这个应该是很多人使用NLog不成功的一个巨坑!
至于网文中及NLog文档中介绍的:加入 aotuReload="true" 属性的办法,不起作用,不知道是不是我有没有注意到的方法。
4、收集的讲解NLog比较详细的文章:
http://www.cnblogs.com/sorex/archive/2013/01/31/2887174.html
http://www.cnblogs.com/Gyoung/archive/2012/10/18/2729613.html
http://blog.csdn.net/viviachen/article/details/19171661
http://www.cnblogs.com/Irving/p/3449048.html(这个很不错)