今天早些时候,我提出了一个有关从代码配置log4net的问题,并很快得到了答案,这使我能够将其配置为输出到文本文件。自那以后,我的需求发生了变化,我需要使用SqLite作为附加程序。因此,我创建了以下类以允许此操作:
public static class SqLiteAppender
{
public static IAppender GetSqliteAppender(string dbFilename)
{
var dbFile = new FileInfo(dbFilename);
if (!dbFile.Exists)
{
CreateLogDb(dbFile);
}
var appender = new AdoNetAppender
{
ConnectionType = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite",
ConnectionString = String.Format("Data Source={0};Version=3;", dbFilename),
CommandText = "INSERT INTO Log (Date, Level, Logger, Message) VALUES (@Date, @Level, @Logger, @Message)"
};
appender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Date",
DbType = DbType.DateTime,
Layout = new log4net.Layout.RawTimeStampLayout()
});
appender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Level",
DbType = DbType.String,
Layout = new log4net.Layout.RawPropertyLayout { Key = "Level" }
});
appender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Logger",
DbType = DbType.String,
Layout = new log4net.Layout.RawPropertyLayout { Key = "LoggerName" }
});
appender.AddParameter(new AdoNetAppenderParameter
{
ParameterName = "@Message",
DbType = DbType.String,
Layout = new log4net.Layout.RawPropertyLayout { Key = "RenderedMessage" }
});
appender.BufferSize = 100;
appender.ActivateOptions();
return appender;
}
public static void CreateLogDb(FileInfo file)
{
using (var conn = new SQLiteConnection())
{
conn.ConnectionString = string.Format("Data Source={0};New=True;Compress=True;Synchronous=Off", file.FullName);
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText =
@"CREATE TABLE Log(
LogId INTEGER PRIMARY KEY,
Date DATETIME NOT NULL,
Level VARCHAR(50) NOT NULL,
Logger VARCHAR(255) NOT NULL,
Message TEXT DEFAULT NULL
);";
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
}
}
问题在于,虽然数据库已创建并添加了表,但我没有得到任何关于此的日志记录。
该类的使用方式如下:
BasicConfigurator.Configure(SqLiteAppender.GetSqliteAppender(applicationContext.GetLogFile().FullName));
任何能够指引我朝正确方向前进的帮助,将不胜感激。
谢谢。