Recently studied Nlog this log frame, here to record how to write the log to SQLite.
First step: Use NuGet to get nlog and SQLite
- The second step: Create a database in SQLite, here I use the SQLite Expert Personal visualization tool
The third step: Configure the target node in the Nlog.config, this in Nlog's official website did not find the corresponding example, but there is a blog on the web has a corresponding record, so first refer to the following:
<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>
But this is only a reference, first we get the SQLite version is not 1.0.65.0, so to modify the string in the Dbprovider, here can be used Ilspay view
This is basically the case, but the latest nlog needs to be added in the configuration:
CommandType = " Text "
So the final configuration is as follows:
<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>
So that we can use Nlog to log the logs directly in the code.
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();
Finally, we use SQLite Expert personal to see if the record is successful:
Nlog Logging to SQLite