方法 1修改 IHttpModule 对象的源代码,以便将异常信息记录到应用程序日志中。记录的信息将包含以下内容: 出现异常的虚拟目录路径 异常名称 消息 堆栈跟踪 要修改 IHttpModule 对象,请按照下列步骤操作。 注意:此代码将会在应用程序日志中记录事件类型为“错误”且事件来源为“ASP.NET 2.0.50727.0”的消息。要测试模块,可以请求使用 ThreadPool.QueueUserWorkItem 方法的 ASP.NET 页,以调用引发未处理的异常的方法。 将下面的代码放在名为 UnhandledExceptionModule.cs 的文件中。 复制代码 代码如下: using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Web; namespace WebMonitor { public class UnhandledExceptionModule: IHttpModule { static int _unhandledExceptionCount = 0; static string _sourceName = null; static object _initLock = new object(); static bool _initialized = false; public void Init(HttpApplication app) { // Do this one time for each AppDomain. if (!_initialized) { lock (_initLock) { if (!_initialized) { string webenginePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "webengine.dll"); if (!File.Exists(webenginePath)) { throw new Exception(String.Format(CultureInfo.InvariantCulture, "Failed to locate webengine.dll at "{0}". This module requires .NET Framework 2.0.", webenginePath)); } FileVersionInfo ver = FileVersionInfo.GetVersionInfo(webenginePath); _sourceName = string.Format(CultureInfo.InvariantCulture, "ASP.NET {0}.{1}.{2}.0", ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart); if (!EventLog.SourceExists(_sourceName)) { throw new Exception(String.Format(CultureInfo.InvariantCulture, "There is no EventLog source named "{0}". This module requires .NET Framework 2.0.", _sourceName)); } AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException); _initialized = true; } } } } public void Dispose() { } void OnUnhandledException(object o, UnhandledExceptionEventArgs e) { // Let this occur one time for each AppDomain. if (Interlocked.Exchange(ref _unhandledExceptionCount, 1) != 0) return; StringBuilder message = new StringBuilder("
UnhandledException logged by UnhandledExceptionModule.dll:
appId="); string appId = (string) AppDomain.CurrentDomain.GetData(".appId"); if (appId != null) { message.Append(appId); }