萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Application_End 記錄網站停止原因至 Log 與 Windows 事件檢視器

為什麼要記錄停止原因?

ASP.NET 應用程式可能因「應用程式集區回收」、「Web.config 變更」、「記憶體限制觸發」、「人為停止」、「未處理例外」等原因重啟。生產環境若無日誌,事後難以追查間歇性服務中斷根因。

核心實作:反射讀取 HttpRuntime 內部欄位

using System;
using System.Reflection;
using System.Web;
using System.Diagnostics;

public class AppLifecycleLogger
{
    public static void LogShutdownReason()
    {
        try
        {
            // 取得 HttpRuntime 靜態單例 _theRuntime
            Type rtType = typeof(HttpRuntime);
            FieldInfo runtimeField = rtType.GetField("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static);
            object runtime = runtimeField?.GetValue(null);
            if (runtime == null) return;

            // 讀取關機訊息與堆疊
            FieldInfo msgField = runtime.GetType().GetField("_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo stackField = runtime.GetType().GetField("_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance);

            string message = msgField?.GetValue(runtime)?.ToString() ?? "Unknown";
            string stack = stackField?.GetValue(runtime)?.ToString() ?? "Unknown";

            string logEntry = $"[Application_End] {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}\n" +
                              $"Message: {message}\nStack:\n{stack}";

            // 1. 寫入應用程式日誌 (Log4Net / Serilog / NLog / 自訂)
            LogHelper.WriteError(logEntry); // 假設專案有 LogHelper

            // 2. 寫入 Windows 事件檢視器 (需事件來源已註冊)
            WriteEventLog(logEntry);

            // 3. 發送警報郵件/Slack/Teams (可選)
            // AlertService.Send("應用程式關閉", logEntry);
        }
        catch (Exception ex)
        {
            // 避免記錄本身失敗導致更多問題
            try { LogHelper.WriteError($"[AppLifecycleLogger] 記錄失敗: {ex}"); } catch { }
        }
    }

    private static void WriteEventLog(string message)
    {
        const string source = "ASP.NET Application";
        if (!EventLog.SourceExists(source))
        {
            try { EventLog.CreateEventSource(source, "Application"); } catch { return; } // 需管理員權限
        }
        using (var log = new EventLog("Application") { Source = source })
        {
            log.WriteEntry(message, EventLogEntryType.Information, 1001);
        }
    }
}

Global.asax 掛載

void Application_End(object sender, EventArgs e)
{
    AppLifecycleLogger.LogShutdownReason();
}

常見關機訊息解讀

訊息關鍵字原因對策
Configuration changedWeb.config / Machine.config / 應用程式目錄下檔案異動鎖定部署流程、避免熱更新、使用預編譯部署
Idle timeout應用程式集區閒置超過預設 20 分鐘自動關閉設定 `IdleTimeout=00:00:00` (停用) 或排程定期喚醒
Memory limit exceeded私有記憶體/虛擬記憶體超過集區限制分析記憶體洩漏、調整限制、啟用定期回收
Request limit達到 `RequestQueueLimit` / `MaxRequests`調高限制、優化長時間請求
Application pool recycle定時回收 (預設 1740 分鐘) 或特定時間回收錯峰設定、預熱頁面
Unhandled exception未捕捉例外導致進程崩潰 (W3WP.exe 終止)全域例外處理、健康檢查、APM 監控
HostingEnvironment initiated shutdownIIS 管理員手動停止/重啟網站/應用程式集區記錄操作人員、變更管理流程

進階:ASP.NET Core / .NET 6+ 內建支援

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddEventLog(); // 直接寫入 Windows Event Log
builder.Host.UseWindowsService(); // 作為 Windows Service 運行時

var app = builder.Build();
app.Lifetime.ApplicationStopping.Register(() => 
{
    var logger = app.Services.GetRequiredService>();
    logger.LogInformation("Application is shutting down...");
});
app.Run();
copyright © 萬盛學電腦網 all rights reserved