.net MVC Nlog使用
1、NLog dll 引用
2、添加 NLog.config 配置文件
<?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. --> <targets> <!-- add your targets here --> <!-- 记录一般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 xsi:type="File" fileName="${basedir}/logs/${shortdate}.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> </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" /> <logger name="*" minlevel="Debug" writeTo="f" /> </rules> </nlog>
3、程序使用
private Logger Logger = LogManager.GetCurrentClassLogger(); public ActionResult Index() { Logger.Info("testlog记录"); Logger.Error("222testlog记录"); return View(); }