日期:2014-05-18 浏览次数:20786 次
using System; using System.Data; using System.Diagnostics; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.EnterpriseLibrary.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using System.Data.Common; namespace Helper { [ConfigurationElementType(typeof(CustomTraceListenerData))] public class ExceptionCustomerListener : CustomTraceListener { /// <summary> /// 数据库连接 /// </summary> private Database db; public ExceptionCustomerListener ( ) { db = DBHelper.CreateDataBase ( ); } #region Overrides of TraceListener public override void TraceData ( TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data ) { if (this.Filter == null || this.Filter.ShouldTrace ( eventCache, source, eventType, id, null, null, data, null )) { if (data is LogEntry) { ExecuteWriteLogSQL ( data as LogEntry ); } else if (data is String) { Write ( data ); } else { base.TraceData ( eventCache, source, eventType, id, data ); } } } public override void Write ( string message ) { String messing = Utils.GetBetweenString ( message, "Message :", "Source :", 9 ); string exceptionInfo = Utils.GetBetweenString ( message, "Stack Trace :", "Additional Info:", 13 ); StringBuilder sb = new StringBuilder ( ); sb.Append ( "insert into ExceptionLog values (" ); sb.Append ( "(SELECT max(id)+1 FROM ExceptionLog)," ); sb.Append ( "@Message" ); sb.Append ( "@LogDate" ); sb.Append ( "@ExceptionLevel" ); sb.Append ( "@Exception" ); DbCommand com = db.GetSqlStringCommand ( sb.ToString ( ) ); //添加参数 db.AddInParameter ( com, "@Message", DbType.String, messing ); db.AddInParameter ( com, "@LogDate", DbType.String, DateTime.Now ); db.AddInParameter ( com, "@ExceptionLevel", DbType.String, message ); db.AddInParameter ( com, "@Exception", DbType.String, exceptionInfo ); int x = db.ExecuteNonQuery ( com ); } public override void WriteLine ( string message ) { Write ( message ); } #endregion /// <summary> /// 日志写入数据库 /// </summary> /// <param name="log"></param> private void ExecuteWriteLogSQL ( LogEntry log ) { String messing = Utils.GetBetweenString ( log.Message, "Message :", "Source :", 9 ); string exceptionInfo = Utils.GetBetweenString ( log.Message, "Stack Trace :", "Additional Info:", 13 ); StringBuilder sb = new StringBuilder ( ); sb.Append ( "insert into ExceptionLog values (" ); sb.Append ( "(SELECT max(id)+1 FROM ExceptionLog)," ); sb.Append ( "@Message" ); sb.Append ( &quo