SQLiteTraceListener

今天整个小东西用到条件编译(ConditionalAttribute),开发时要记录些日志,一切从简用了Trace.WriteLine() V.S. Debug.WriteLine(), 使用过程中发现默认提供的几个TraceListener都不咋符合要求。顺便就开发了个SQLiteTraceListener。通过Trace.WriteLine() 将日志信息记入到SQLite数据库文件中。

1) 安装SQLite相关东东

SQLite Precompiled Binaries For Windows
sqlite-shell-win32-x86-3070701.zip
sqlite-dll-win32-x86-3070701.zip
sqlite-analyzer-win32-x86-3070701.zip
Setups for 32-bit Windows (.NET Framework 4.0)
sqlite-netFx40-setup-bundle-x86-2010-1.0.74.0.exe
SQLite Administrator - International Milestone Beta
SQLite Administrator [0.8.3.2]

2) 建立日志表

3) 开发SQLiteTraceListener

View Code
using System;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Specialized ;
using System.Data;
using System.Data.SQLite;
using System.Data.Common;
using System.Windows.Forms;


namespace MyLab.CommonLibrary
{
public class SQLiteTraceListener : TraceListener
{
private const string COLUMN_SEPARATOR = "|" ;
private string m_strConnectionString ;
private int m_iMaximumRequests ;
private StringCollection m_objCollection ;

public SQLiteTraceListener()
{
InitializeListener() ;
}

public SQLiteTraceListener(string r_strListenerName)
:
base(r_strListenerName)
{
InitializeListener() ;
}

private void InitializeListener()
{
m_strConnectionString
= "Data Source=" + Application.StartupPath + "\\TraceLog.s3db";
m_iMaximumRequests
= Convert.ToInt32(ConfigurationManager.AppSettings["MaximumRequests"]) ;
m_objCollection
= new StringCollection() ;
}

private void SaveErrors()
{
SQLiteConnection objConnection
= new SQLiteConnection(m_strConnectionString);
SQLiteCommand objCommand
= new SQLiteCommand();
try
{
string sql = @"INSERT INTO Traces(TraceDateTime,TraceCategory,TraceDescription,StackTrace,DetailedErrorDescription)VALUES(@TraceDateTime,@TraceCategory,@TraceDescription,@StackTrace,@DetailedErrorDescription)";
objCommand.Connection
= objConnection ;
objCommand.CommandText
= sql;
objCommand.CommandType
= CommandType.Text;
objConnection.Open() ;

foreach (string m_strError in m_objCollection)
{
//CreateParameters(objCommand, m_strError) ;
if ((objCommand != null) && (!m_strError.Equals("")))
{
string[] strColumns;
strColumns
= m_strError.Split(COLUMN_SEPARATOR.ToCharArray());
SQLiteParameter[] parameters
= new SQLiteParameter[]{
new SQLiteParameter("@TraceDateTime",strColumns.GetValue(0).ToString().Trim()),
new SQLiteParameter("@TraceCategory",strColumns.GetValue(1).ToString().Trim()),
new SQLiteParameter("@TraceDescription",strColumns.GetValue(2).ToString().Trim()),
new SQLiteParameter("@StackTrace",strColumns.GetValue(3).ToString().Trim()),
new SQLiteParameter("@DetailedErrorDescription",strColumns.GetValue(4).ToString().Trim())};
objCommand.Parameters.Clear();
objCommand.Parameters.AddRange(parameters);
}
objCommand.ExecuteNonQuery() ;
}
m_objCollection.Clear() ;
}
catch (Exception e)
{

}
finally
{
if (objConnection != null)
{
if (objConnection.State == ConnectionState.Open)
objConnection.Close() ;
}
objConnection
= null ;
objCommand
= null ;
}
}

private void AddToCollection( string r_strTraceDateTime,
string r_strTraceCategory,
string r_strTraceDescription,
string r_strStackTrace,
string r_strDetailedErrorDescription)
{
string strError = r_strTraceDateTime + COLUMN_SEPARATOR +
r_strTraceCategory
+ COLUMN_SEPARATOR +
r_strTraceDescription
+ COLUMN_SEPARATOR +
r_strStackTrace
+ COLUMN_SEPARATOR +
r_strDetailedErrorDescription ;
m_objCollection.Add(strError) ;
if (m_objCollection.Count == m_iMaximumRequests)
{
SaveErrors() ;
}
}

//private void CreateParameters(SQLiteCommand r_objCommand, string r_strError)
//{
// if ( (r_objCommand != null) && (! r_strError.Equals("")) )
// {
// string[] strColumns ;
// SQLiteParameterCollection objParameters = r_objCommand.Parameters;

// strColumns = r_strError.Split(COLUMN_SEPARATOR.ToCharArray()) ;
// objParameters.Clear() ;

//objParameters.Add(new SQLiteParameter("@TraceDateTime",
// DbType.DateTime,
// 8) ) ;
//objParameters.Add(new SQLiteParameter("@TraceCategory",
// DbType.String,
// 50) ) ;
//objParameters.Add(new SQLiteParameter("@TraceDescription",
// DbType.String,
// 1024) ) ;
//objParameters.Add(new SQLiteParameter("@StackTrace",
// DbType.String,
// 2048) ) ;
//objParameters.Add(new SQLiteParameter("@DetailedErrorDescription",
// DbType.String,
// 2048) ) ;

// int iCount = strColumns.GetLength(0) ;
// for (int i = 0; i < iCount; i++)
// {
// objParameters[i].IsNullable = true ;
// objParameters[i].Direction = ParameterDirection.Input ;
// objParameters[i].Value = strColumns.GetValue(i).ToString().Trim() ;
// }
// }
//}

public override void Write(string message)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString() ,
"", message, objTrace.ToString(), "" ) ;
}

public override void Write(object o)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString(),
"", o.ToString() , objTrace.ToString(), "" ) ;
}

public override void Write(string message, string category)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString() , category , message, objTrace.ToString(),
"" ) ;
}

public override void Write(object o, string category)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString() , category, o.ToString(), objTrace.ToString(),
"" ) ;
}


public override void WriteLine(string message)
{
Write(message
+ "\n") ;
}

public override void WriteLine(object o)
{
Write(o.ToString()
+ "\n") ;
}

public override void WriteLine(string message, string category)
{
Write((message
+ "\n"), category) ;
}

public override void WriteLine(object o, string category)
{
Write( (o.ToString()
+ "\n"), category) ;
}


public override void Fail(string message)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString(),
"Fail", message, objTrace.ToString(), "") ;
}

public override void Fail(string message, string detailMessage)
{
StackTrace objTrace
= new StackTrace(true) ;
AddToCollection(DateTime.Now.ToString(),
"Fail", message, objTrace.ToString(), detailMessage) ;
}

public override void Close()
{
SaveErrors() ;
}

public override void Flush()
{
SaveErrors() ;
}
}
}
4) 测试相关功能
View Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MaximumRequests" value="2" />
</appSettings>
<system.diagnostics>
<trace autoflush="true" indentsize="2">
<listeners>
<add name="DBTL"
type
="MyLab.CommonLibrary.SQLiteTraceListener,MyLab.CommonLibrary"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
View Code
object obj1 = "Message from Trace.Write(object)";
object obj2 = "Message from Trace.Write(object, category)";

Trace.Write(
"Message from Trace.Write(message)");
Trace.Write(obj1);
Trace.Write(
"Message from Trace.Write(message, category)", "category");
Trace.Write(obj2,
"category");

Trace.WriteLine(
"Message from Trace.WriteLine");
Trace.Fail(
"Message from Trace.Fail");
Trace.Fail(
"Message from Trace.Fail", "Detailed error message");

Trace.Flush();

5) 日志结果


6) 问题
貌似中文支持有点问题。处理中...

代码下载

参考资料列表:
http://www.cnblogs.com/a_ming/archive/2011/04/18/2019704.html
http://www.cnblogs.com/longshen/archive/2009/10/28/1591647.html
http://www.cnblogs.com/artech/archive/2011/04/06/conditionalcompilation.html

posted @ 2011-07-12 01:11  知生知死  阅读(642)  评论(0编辑  收藏  举报