使用Microsoft.ApplicationBlocks.ExceptionManagement处理程序异常
详细文档看:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/emab-rm.asp
说明几点:
文件夹:Microsoft.ApplicationBlocks.ExceptionManagement
为异常主类文件.
Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces
为异常接口类文件,
安装
1.使用installutil安装DLL文件,
安装方法,
Visual Studio .NET 2003 命令提示+installutil Microsoft.ApplicationBlocks.ExceptionManagement.dll所有路径
如:installutil E:\exception\Microsoft.ApplicationBlocks.ExceptionManagement\bin\Debug\Microsoft.ApplicationBlocks.ExceptionManagement.dll
程序使用:
添加对Microsoft.ApplicationBlocks.ExceptionManagement.dll引用,
在配制文件添加配制
<configSections>
<section name="exceptionManagement" type="Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManagerSectionHandler,Microsoft.ApplicationBlocks.ExceptionManagement" />
</configSections>
<exceptionManagement mode="on">
<!--使用自定义数据记录使用下面配制-->
<!--<publisher mode="on"
assembly="Microsoft.ApplicationBlocks.ExceptionManagement"
type="Edobnet.FrameWork.ExceptionHandler.ExceptionDBPublisher"
connString="USER ID=sa;PASSWORD=232323;INITIAL CATALOG=Errors;DATA SOURCE=localhost" />-->
<!--使用自定义数据记录使用下面配制-->
<!--<publisher mode="on"
assembly="Microsoft.ApplicationBlocks.ExceptionManagement"
type="Edobnet.FrameWork.ExceptionHandler.ExceptionLogPublisher"
fileName="philips.log"
filePath="C:"
stackTrace = "true"
daily="true" />
-->
</exceptionManagement>
<section name="exceptionManagement" type="Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManagerSectionHandler,Microsoft.ApplicationBlocks.ExceptionManagement" />
</configSections>
<exceptionManagement mode="on">
<!--使用自定义数据记录使用下面配制-->
<!--<publisher mode="on"
assembly="Microsoft.ApplicationBlocks.ExceptionManagement"
type="Edobnet.FrameWork.ExceptionHandler.ExceptionDBPublisher"
connString="USER ID=sa;PASSWORD=232323;INITIAL CATALOG=Errors;DATA SOURCE=localhost" />-->
<!--使用自定义数据记录使用下面配制-->
<!--<publisher mode="on"
assembly="Microsoft.ApplicationBlocks.ExceptionManagement"
type="Edobnet.FrameWork.ExceptionHandler.ExceptionLogPublisher"
fileName="philips.log"
filePath="C:"
stackTrace = "true"
daily="true" />
-->
</exceptionManagement>
添加USING
using Microsoft.ApplicationBlocks.ExceptionManagement;
测试代码:
try
{
int t = 0;
int i = 1/t;
}
catch(Exception ex)
{
ExceptionManager.Publish( ex );
}
{
int t = 0;
int i = 1/t;
}
catch(Exception ex)
{
ExceptionManager.Publish( ex );
}
如果不使用自己定议异常处理,只会在WINDOWS事件里记录,
自定义异常处理:
using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.ApplicationBlocks.ExceptionManagement;
namespace Edobnet.FrameWork.ExceptionHandler
{
/// <summary>
/// <para>
/// This ExceptionDBPublisher class is a custom publisher for the
/// Microsoft Exception Management Application Block.
/// </para><para>
/// It writes Exception info to a database including
/// Message, Source and Stack Trace.
/// </para>
/// </summary>
/// <remarks>
/// <para>This class is a custom publisher for the
/// Microsoft Exception Management Application Block.
/// Note that the Stored Procedure spLogError and table
/// ErrorLog must exist in the database.
/// It writes Exception info to a database including:
/// <list type="bullet">
/// <item><term>Message</term>
/// <description>Exception Message</description></item>
/// <item><term>Source</term>
/// <description>The Exception source</description></item>
/// <item><term>StackTrace</term>
/// <description>The Stack Trace</description></item></list>
/// </para>
/// <para>
/// Configuration Parameters and examples:
/// <list type="bullet">
/// <item>
/// <term>assembly</term>
/// <description>assembly file name: assembly="[Dll name without '.dll']"</description>
/// </item>
/// <item>
/// <term>type</term>
/// <description>class and namespace: type="[Fully qualified namespace and type]"</description>
/// </item>
/// <item>
/// <term>connString</term>
/// <description>Connection String: connString="db_connect_string"</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// For more information see documentation on MS Exception Management
/// Application Blocks</para>
/// <example>Here is an example entry under <exceptionManagement>"
/// <code>
/// <publisher mode="on"
/// assembly="Com.Daveranck.ExceptionHandler"
/// type="Com.Daveranck.ExceptionHandler.ExceptionDBPublisher"
/// connString="server=[Server Name];Integrated Security=SSPI;Database=[Database]" />
/// </code>
/// </example>
/// </remarks>
public class ExceptionDBPublisher : IExceptionPublisher
{
/// <summary>
/// The database connection string must be set in config file
/// </summary>
// MUST be set in config file
private string m_ConnString = @"";
/// <summary>
/// Constructor
/// </summary>
public ExceptionDBPublisher()
{
}
/// <summary>
/// Sets up the config settings from the app
/// config file, if available. Otherewise,
/// defaults are used.
/// </summary>
private void SetConfig(NameValueCollection configSettings)
{
// Load Config values if they are provided.
if (configSettings != null)
{
if (configSettings["connString"] != null &&
configSettings["connString"].Length > 0)
{
m_ConnString = configSettings["connString"];
}
}
}
/// <summary>
/// Provide implementation of the IExceptionPublisher interface
/// This contains the single Publish method.
/// <param name="exception">Exception</param>
/// <param name="additionalInfo">NameValuecollection</param>
/// <param name="configSettings">NameValuecollection</param>
/// </summary>
void IExceptionPublisher.Publish(Exception exception,
NameValueCollection additionalInfo,
NameValueCollection configSettings)
{
// Load config settings if available
SetConfig(configSettings);
// Create StringBuilder to maintain publishing information.
StringBuilder strInfo = new StringBuilder();
// Record the contents of the additionalInfo collection.
if (additionalInfo != null)
{
// Record General information.
strInfo.AppendFormat("{0}General Information {0}", Environment.NewLine);
strInfo.AppendFormat("{0}Additonal Info:", Environment.NewLine);
foreach (string i in additionalInfo)
{
strInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i,
additionalInfo.Get(i));
}
}
// Log to database
LogInDatabase(strInfo.ToString(),
exception.Message,
exception.Source,
exception.StackTrace);
}
/// <summary>
/// <para>This method will publish the Exception Message,
/// Source and Stack Trace to a database.</para>
/// </summary>
/// <param name="Info">General exception info</param>
/// <param name="Message">Excaption Mesage</param>
/// <param name="Source">Exception Source</param>
/// <param name="StackTrace">Exception Stack Trace</param>
private void LogInDatabase(string Info,
string Message,
string Source,
string StackTrace)
{
// Create connection
SqlConnection sqlConn = new SqlConnection();
sqlConn.ConnectionString = m_ConnString;
string spName = "spLogError";
SqlCommand sqlCmd = new SqlCommand(spName, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
// Add params
SqlParameter pInfo = sqlCmd.Parameters.Add("@Info", SqlDbType.VarChar, 500);
pInfo.Value = Info;
SqlParameter pMessage = sqlCmd.Parameters.Add("@Message", SqlDbType.VarChar, 500);
pMessage.Value = Message;
SqlParameter pSource = sqlCmd.Parameters.Add("@Source", SqlDbType.VarChar, 255);
pSource.Value = Source;
SqlParameter pStackTrace = sqlCmd.Parameters.Add("@StackTrace", SqlDbType.VarChar, 1000);
pStackTrace.Value = StackTrace;
// Log error
try
{
sqlConn.Open();
int result = sqlCmd.ExecuteNonQuery();
}
catch(Exception ex)
{
// Database problem rethrow exception
// Exception Manager will log original exception
// and this exception to Event log
throw ex;
}
finally
{
// Clean up
if (sqlConn.State != System.Data.ConnectionState.Closed &&
sqlConn.State != System.Data.ConnectionState.Broken)
{
sqlConn.Close();
}
}
}
}
/// <summary>
/// <para>The ExceptionLogPublisher class is a custom publisher for the
/// Microsoft Exception Management Application Block.
/// </para><para>
/// It writes exception info to a logfile including:
/// Message and optionally Source and StackTrace.
/// </para>
/// </summary>
/// <remarks>
/// <para>Configuration Parameters and examples:
/// <list type="bullet">
/// <item>
/// <term>assembly</term>
/// <description>assembly file name: assembly="[Dll name without '.dll']"</description>
/// </item>
/// <item>
/// <term>type</term>
/// <description>class and namespace: type="[Fully qualified namespace and type]"</description>
/// </item>
/// <item>
/// <term>fileName</term>
/// <description>log file name: "myLogFile.txt"</description>
/// </item>
/// <item>
/// <term>filePath</term>
/// <description>path to log file location (including trailing ""): "c:logs</description>
/// </item>
/// <item>
/// <term>stackTrace</term>
/// <description>true or false - if true, stack trace included in log</description>
/// </item>
/// <item>
/// <term>daily</term>
/// <description>true or false - if true, new log created each day and date
/// preppended to the fileName Ex: 20031114myLogFile.log</description>
/// </item>
/// </list>
/// <para>For more information see documentation on MS Exception Management
/// Application Blocks</para>
/// </para>
/// <example>Here is an example entry under <exceptionManagement>
/// <code>
/// <publisher mode="on"
/// assembly="Com.Daveranck.ExceptionHandler"
/// type="Com.Daveranck.ExceptionHandler.ExceptionLogPublisher"
/// fileName="AppExceptionLog.txt"
/// filePath="c:"
/// stackTrace = "true"
/// daily="true" />
/// </code>
/// </example>
/// </remarks>
public class ExceptionLogPublisher : IExceptionPublisher
{
// defaults if no parameteres given
private string m_LogName = @"ErrorLog.txt";
private string m_LogPath = @"C:";
private bool m_dailyLog = false;
private bool m_stackTrace = false;
/// <summary>
/// Constructor
/// </summary>
public ExceptionLogPublisher()
{
}
/// <summary>
/// Sets up the config settings from the app
/// config file, if available. Otherewise,
/// defaults are used.
/// </summary>
private void SetConfig(NameValueCollection configSettings)
{
// Load Config values if they are provided.
if (configSettings != null)
{
if (configSettings["fileName"] != null &&
configSettings["fileName"].Length > 0)
{
m_LogName = configSettings["fileName"];
}
if (configSettings["filePath"] != null &&
configSettings["filePath"].Length > 0)
{
m_LogPath = configSettings["filePath"];
}
if(configSettings["daily"] != null &&
configSettings["daily"].Equals("true"))
{
m_dailyLog = true;
}
if(configSettings["stackTrace"] != null &&
configSettings["stackTrace"].Equals("true"))
{
m_stackTrace = true;
}
}
}
/// <summary>
/// Crestes the file path to write the log file to.
/// If Daily has been set to true in config settings,
/// will prepend the date (yyyymmdd) to the filename,
/// allowing the file to rollover daily.
/// </summary>
/// <returns>string Filename and path</returns>
private string CreateLogFilePath()
{
if(m_dailyLog == true)
{
//Add date header to filename
DateTime dt = DateTime.Today;
StringBuilder newLogName = new StringBuilder();
newLogName.Append(dt.Year.ToString());
newLogName.Append(dt.Month.ToString());
newLogName.Append(dt.Day.ToString());
newLogName.Append(m_LogName);
m_LogName = newLogName.ToString();
}
string logFilePath = m_LogPath + m_LogName;
return logFilePath;
}
/// <summary>
/// Creates the message to be logged from the Exception.
/// Will add additional info if it exists and if
/// stackTrace is true in config settings, will append stack trace
/// and source to the message.
/// </summary>
/// <returns>string message to log</returns>
private string CreateLogMessage(Exception exception,
NameValueCollection additionalInfo)
{
// Create StringBuilder to maintain publishing information.
StringBuilder strInfo = new StringBuilder();
// Record the contents of the additionalInfo collection.
if (additionalInfo != null)
{
// Record General information.
strInfo.AppendFormat("{0}General Information {0}", Environment.NewLine);
strInfo.AppendFormat("{0}Additonal Info:", Environment.NewLine);
foreach (string i in additionalInfo)
{
strInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i,
additionalInfo.Get(i));
}
}
// Append the exception text including:
// Message and if stackTrace = true, Source and Stack Trace
if ( exception != null )
{
strInfo.AppendFormat("{0}Exception Information {1}",
Environment.NewLine, exception.Message.ToString() + Environment.NewLine);
//Append Source and Stacktrace
if(m_stackTrace == true)
{
strInfo.Append(Environment.NewLine + "Source: ---- " + Environment.NewLine
+ exception.Source + Environment.NewLine);
strInfo.Append(Environment.NewLine + "Stack Trace: ---- "
+ Environment.NewLine + exception.StackTrace);
}
strInfo.Append(Environment.NewLine
+ "------------------------------------------------------------"
+ Environment.NewLine + Environment.NewLine);
}
else
{
strInfo.AppendFormat("{0}{0}No Exception.{0}", Environment.NewLine);
}
return strInfo.ToString();
}
/// <summary>
/// Provide implementation of the IExceptionPublisher interface
/// This contains the single Publish method.
/// <para>Logs the Exception Message, Source and Stack Trace</para>
/// </summary>
/// <param name="exception">Exception</param>
/// <param name="additionalInfo">NameValuecollection</param>
/// <param name="configSettings">NameValuecollection</param>
void IExceptionPublisher.Publish(Exception exception,
NameValueCollection additionalInfo,
NameValueCollection configSettings)
{
// Read and set up configuration
SetConfig(configSettings);
// Create fileName
string logFilePath = CreateLogFilePath();
// Create Message
string logMessage = CreateLogMessage(exception, additionalInfo);
// Write the entry to the log file.
try
{
// Append to file if exists or create new file
using ( FileStream fs = File.Open(logFilePath,
FileMode.Append,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(logMessage);
}
}
}
catch(Exception ex)
{
// Error writing exception.
// Exception Manager will log original exception
// and this exception to Event log
throw ex;
}
}
}
}
数据库异常的数据表如下:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ErrorLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[ErrorLog]
GO
CREATE TABLE [dbo].[ErrorLog] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Info] [varchar] (500) NOT NULL ,
[Message] [varchar] (500) NULL ,
[Source] [varchar] (255) NULL ,
[StackTrace] [varchar] (1000) NULL ,
[EntryDateTime] [datetime] NOT NULL
) ON [PRIMARY]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spLogError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spLogError]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
/*********************************************************************************************************************************************************************************************
Name: spLogError
Author: Dave Ranck
Date: 11/14/2003
Purpose: This procedure logs exception info.
Parameters: @Info
@Message
@Source
@StackTrace
/*********************************************************************************************************************************************************************************************/
*/
CREATE PROCEDURE spLogError
@Info varchar(500),
@Message varchar(500),
@Source varchar(255),
@StackTrace varchar (2000)
AS
INSERT INTO ErrorLog(Info, Message, Source, StackTrace, EntryDateTime)
VALUES(@Info, @Message, @Source, @StackTrace, GetDate())
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
drop table [dbo].[ErrorLog]
GO
CREATE TABLE [dbo].[ErrorLog] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Info] [varchar] (500) NOT NULL ,
[Message] [varchar] (500) NULL ,
[Source] [varchar] (255) NULL ,
[StackTrace] [varchar] (1000) NULL ,
[EntryDateTime] [datetime] NOT NULL
) ON [PRIMARY]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spLogError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spLogError]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
/*********************************************************************************************************************************************************************************************
Name: spLogError
Author: Dave Ranck
Date: 11/14/2003
Purpose: This procedure logs exception info.
Parameters: @Info
@Message
@Source
@StackTrace
/*********************************************************************************************************************************************************************************************/
*/
CREATE PROCEDURE spLogError
@Info varchar(500),
@Message varchar(500),
@Source varchar(255),
@StackTrace varchar (2000)
AS
INSERT INTO ErrorLog(Info, Message, Source, StackTrace, EntryDateTime)
VALUES(@Info, @Message, @Source, @StackTrace, GetDate())
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
设定相应的异常通过CONFIG文件来设置,我在接面有相应的例子.