我正在嘗試在NLog中使用SQLite,這樣我就可以將日誌記錄存儲到SQLite數據庫而不是平面文件。我遵循了一個很好的教程,但即使如此,我的代碼沒有啓用按預期工作。如何在NET中使用SQLite和NLog
我App.config
文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="SQLite" connectionString="Data Source=Log.db3;Version=3;" providerName="System.Data.SQLite" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
</configuration>
這是我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">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}"
fileName="${basedir}/logs/${shortdate}/${level}.txt"
keepFileOpen="false"/>
<target name="db" xsi:type="Database" keepConnection="false"
useTransactions="false"
dbProvider="System.Data.SQLite"
connectionString="Data Source=${basedir}\Log.db3;Version=3;"
commandText="INSERT into Log(Timestamp, Loglevel, Callsite, Message) values(@Timestamp, @Loglevel, @Callsite, @Message)">
<parameter name="@Timestamp" layout="${longdate}"/>
<parameter name="@Loglevel" layout="${level:uppercase=true}"/>
<parameter name="@Callsite" layout="${callsite:filename=true}"/>
<parameter name="@Message" layout="${message}"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="db" />
</rules>
</nlog>
這是我的代碼:
static class Program
{
static Logger log = LogManager.GetCurrentClassLogger();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
EnsureDb();
log.Info("Logging like a boss");
Application.Run(new Form1());
}
catch (Exception ex)
{
throw;
}
}
private static void EnsureDb()
{
if (File.Exists("Log.db3"))
return;
using (SQLiteConnection connection = new SQLiteConnection(ConfigurationManager.ConnectionStrings["SQLite"].ToString()))
using (SQLiteCommand command = new SQLiteCommand(
"CREATE TABLE Log (Timestamp TEXT, Loglevel TEXT, Callsite TEXT, Message TEXT)",
connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
我抄這個代碼從互聯網上,但不幸的是它不工作。 log.db3文件總是被創建,但沒有日誌條目到達日誌表。我怎樣才能解決這個問題?
什麼是不工作?你有錯誤嗎? – nemesv 2014-10-27 07:50:30
沒有,我沒有得到創建了一個錯誤,log.db3文件,但日誌表總是空 – Shax 2014-10-27 07:53:36