最近研究了一下Nlog这个日志框架,这里记录一下如何将日志写到sqlite中。
第一步:使用NuGet获取Nlog和Sqlite
第三步:在Nlog.config中配置target节点,这个在Nlog的官网中没有查找到相应的例子,但网上有一篇博客有相应的记载,所以就先参考下:
<target name="Database" xsi:type="Database" keepConnection="false" useTransactions="false" dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" connectionString="Data Source=d:log.db3;Version=3;" commandText="INSERT into Log(Timestamp, Loglevel, Logger, Callsite, Message) values(@Timestamp, @Loglevel, @Logger, @Callsite, @Message)"> <parameter name="@Timestamp" layout="${longdate}"/> <parameter name="@Loglevel" layout="${level:uppercase=true}"/> <parameter name="@Logger" layout="${logger}"/> <parameter name="@Callsite" layout="${callsite:filename=true}"/> <parameter name="@Message" layout="${message}"/> </target>
但这只是参考,首先我们获取的sqlite版本不是1.0.65.0,所以要修改dbProvider中的字符串,这里可以用ILSpay查看
到这里基本上就差不多了,但最新的Nlog需要的配置中还要加上这一句:
commandType="Text"
所以最终的配置如下:
<targets> <!-- add your targets here --> <target name="File" xsi:type="File" fileName="C:Logfiles${shortdate}_nlog.txt"/> <target name="Database" xsi:type="Database" keepConnection="false" useTransactions="false" dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.97.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" connectionString="Data Source=d:log.db3;Version=3;" commandType="Text" commandText="INSERT into Log(Timestamp, Loglevel, Logger, Callsite, Message) values(@Timestamp, @Loglevel, @Logger, @Callsite, @Message)"> <parameter name="@Timestamp" layout="${longdate}"/> <parameter name="@Loglevel" layout="${level:uppercase=true}"/> <parameter name="@Logger" layout="${logger}"/> <parameter name="@Callsite" layout="${callsite:filename=true}"/> <parameter name="@Message" layout="${message}"/> </target> <!-- <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> --> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="Database" /> </rules>
这样我们就可以在代码中直接使用Nlog记录日志了
Logger log = LogManager.GetCurrentClassLogger(); LogManager.ThrowExceptions = true; log.Trace("test begin..."); for (int i = 0; i < 5; i++) { Console.WriteLine(i); log.Debug(i.ToString()); } log.Trace("test end..."); Console.WriteLine("Press any key to close the application"); Console.ReadKey();
最后我们再用SQLite Expert Personal查看下是否记录成功: