ASP.NETプログラムはEvent ViewerにEvent Logを書き込む

2340 ワード

/*By Jiangong SUN*/
Webでconfigのappsettingsへの書き込み
<!--Event Log-->
<add key="EventLog" value="Application" />
<add key="EventSource" value="Project" />

プロジェクトでglobal.asax中
protected void Application_Start(object sender, EventArgs e)
{
   Log.Configure(Settings.EventSource, Settings.EventLog); 
}

ログクラスで
public class Log
    {
        static string source;

        public static void Configure(string eventSource, string eventLog)
        {
            // Create the source, if it does not already exist.
            if (!EventLog.SourceExists(eventSource,"."))
            {
                EventLog.CreateEventSource(eventSource, eventLog);
            }
            source = eventSource;
        }

        public static void Error(string message)
        {
            Write(message, EventLogEntryType.Error);
        }

        public static void Error(string message, Exception e)
        {
            Write(message + "

" + e.ToString(), EventLogEntryType.Error); } public static void Info(string message) { Write(message, EventLogEntryType.Information); } public static void Fatal(string message, Exception e) { Write(message + "

" + e.ToString(), EventLogEntryType.Error); } static void Write(string message, EventLogEntryType type) { EventLog myLog = new EventLog(); myLog.Source = source; myLog.WriteEntry(message, type); } }

Settingsクラスで
public static class Settings
    {
        public static string EventSource
        {
            get
            {
                return WebConfigurationManager.AppSettings["EventSource"];
            }
        }
        public static string EventLog
        {
            get
            {
                return WebConfigurationManager.AppSettings["EventLog"];
            }
        }
}

レジストリを開きます
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application
新しいkeyを作成します.keyの名前はプロジェクトの名前Projectです.