ASP.NET 應用程式可能因「應用程式集區回收」、「Web.config 變更」、「記憶體限制觸發」、「人為停止」、「未處理例外」等原因重啟。生產環境若無日誌,事後難以追查間歇性服務中斷根因。
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);
}
}
}
void Application_End(object sender, EventArgs e)
{
AppLifecycleLogger.LogShutdownReason();
}
| 訊息關鍵字 | 原因 | 對策 |
|---|---|---|
| Configuration changed | Web.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 shutdown | IIS 管理員手動停止/重啟網站/應用程式集區 | 記錄操作人員、變更管理流程 |
// 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();