首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 寫入 Windows 系統事件日誌實作範例

     編輯:關於C#

應用程式若需記錄重要資訊、警告或錯誤到 Windows 事件檢視器,可使用 System.Diagnostics.EventLog 類別。本文提供一個可重複使用的 LogWriter 類別,封裝事件來源建立與寫入邏輯。

LogWriter 類別完整程式碼

using System;
using System.Diagnostics;

namespace Log
{
    public class LogWriter
    {
        private string _eventSourceName = "TestApp";
        private EventLogEntryType _eventLogType = EventLogEntryType.Error;

        public string EventSourceName
        {
            set { _eventSourceName = value; }
        }

        public EventLogEntryType EventLogType
        {
            set { _eventLogType = value; }
        }

        public void LogEvent(string message)
        {
            if (string.IsNullOrEmpty(message)) return;

            // 來源不存在時自動建立(需管理員權限)
            if (!EventLog.SourceExists(_eventSourceName))
            {
                EventLog.CreateEventSource(_eventSourceName, "Application");
            }

            EventLog.WriteEntry(_eventSourceName, message, _eventLogType);
        }
    }
}

使用範例

var logger = new LogWriter();
logger.EventSourceName = "MyService";
logger.EventLogType = EventLogEntryType.Warning;
logger.LogEvent("這是一則測試警告訊息。");

關鍵點提醒

  • 權限需求:CreateEventSource 需管理員權限。建議在安裝程式或應用程式首次以管理員身分執行時預先建立來源,避免執行期拋出 SecurityException。
  • 事件類型:EventLogEntryType 列舉包含 Error、Warning、Information、SuccessAudit、FailureAudit,依實際嚴重程度選擇。
  • 日誌名稱:範例寫入 "Application" 日誌,亦可指定 "System"、"Security" 或自訂日誌名稱。
  • 效能考量:頻繁寫入事件日誌可能影響效能,建議批次處理或使用非同步寫入策略。

進階擴充

可進一步加入:

  • 支援格式化字串與參數陣列的 LogEventFormat 方法。
  • 自動附加時間戳記、執行緒 ID、呼叫堆疊等上下文資訊。
  • 實作 IDisposable 釋放非受控資源(雖然 EventLog 多為靜態方法,較少需求)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved