본문 바로가기
C#

[C#] EventLog (Windows 이벤트 로그)

by DANEW 2023. 10. 26.

EventLog 클래스

 

EventLog 클래스 (System.Diagnostics)

Windows 이벤트 로그 조작을 제공합니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public class EventLog : Component, ISupportInitialize
    {
        public EventLog();
        public EventLog(string logName);
        public EventLog(string logName, string machineName);
        public EventLog(string logName, string machineName, string source);
 
        public ISynchronizeInvoke SynchronizingObject { get; set; }
               
        public int MinimumRetentionDays { get; }
        public OverflowAction OverflowAction { get; }
 
        public long MaximumKilobytes { get; set; }
        public string MachineName { get; set; }
        public string Log { get; set; }
        public string LogDisplayName { get; }
        public EventLogEntryCollection Entries { get; }
        public string Source { get; set; }
 
        public bool EnableRaisingEvents { get; set; }
 
        public event EntryWrittenEventHandler EntryWritten;
 
        public static void CreateEventSource(EventSourceCreationData sourceData);
        public static void CreateEventSource(string source, string logName);
        //public static void CreateEventSource(string source, string logName, string machineName);
 
        public static void Delete(string logName);
        public static void Delete(string logName, string machineName);
        public static void DeleteEventSource(string source);
        public static void DeleteEventSource(string source, string machineName);
       
        public static bool Exists(string logName);
        public static bool Exists(string logName, string machineName);
        public static string LogNameFromSourceName(string source, string machineName);
        public static bool SourceExists(string source);
        public static bool SourceExists(string source, string machineName);
 
        public static EventLog[] GetEventLogs();
        public static EventLog[] GetEventLogs(string machineName);
 
        public static void WriteEntry(string source, string message);
        public static void WriteEntry(string source, string message, EventLogEntryType type);
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID);
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category);
        public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData);
        public static void WriteEvent(string source, EventInstance instance, params object[] values);
        public static void WriteEvent(string source, EventInstance instance, byte[] data, params object[] values);
       
        public void BeginInit();
        public void EndInit();
        public void Clear();
        public void Close();
        protected override void Dispose(bool disposing);
 
        public void ModifyOverflowPolicy(OverflowAction action, int retentionDays);
        public void RegisterDisplayName(string resourceFile, long resourceId);
 
        public void WriteEntry(string message);
        public void WriteEntry(string message, EventLogEntryType type);
        public void WriteEntry(string message, EventLogEntryType type, int eventID);
        public void WriteEntry(string message, EventLogEntryType type, int eventID, short category);
        public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData);
        public void WriteEvent(EventInstance instance, params object[] values);
        public void WriteEvent(EventInstance instance, byte[] data, params object[] values);
    }
}
namespace System.Diagnostics
{
    public enum OverflowAction
    {
        DoNotOverwrite = -1,
        OverwriteAsNeeded = 0,
        OverwriteOlder = 1
    }
}
namespace System.Diagnostics
{
    public enum EventLogEntryType
    {
        Error = 1,
        Warning = 2,
        Information = 4,
        SuccessAudit = 8,
        FailureAudit = 16
    }
}

EventSourceCreationData 클래스

 

EventSourceCreationData 클래스 (System.Diagnostics)

로컬 컴퓨터 또는 원격 컴퓨터에서 이벤트 로그 소스를 만드는 데 사용되는 구성 설정을 나타냅니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public class EventSourceCreationData
    {
        public EventSourceCreationData(string source, string logName);
 
        public string LogName { get; set; }
        public string MachineName { get; set; }
        public string Source { get; set; }
        public string MessageResourceFile { get; set; }
        public string ParameterResourceFile { get; set; }
        public string CategoryResourceFile { get; set; }
        public int CategoryCount { get; set; }
    }
}

EventInstance 클래스

 

EventInstance 클래스 (System.Diagnostics)

이벤트 로그 엔트리에 대한 언어 중립 정보를 나타냅니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public class EventInstance
    {
        public EventInstance(long instanceId, int categoryId);
        public EventInstance(long instanceId, int categoryId, EventLogEntryType entryType);
       
        public int CategoryId { get; set; }
        public EventLogEntryType EntryType { get; set; }
        public long InstanceId { get; set; }
    }
}

EventLogEntryCollection 클래스

 

EventLogEntryCollection 클래스 (System.Diagnostics)

EventLogEntry 인스턴스의 컬렉션에 대한 크기 및 열거자를 정의합니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public class EventLogEntryCollection : ICollection, IEnumerable
    {
        public virtual EventLogEntry this[int index] { get; }
        public int Count { get; }        
        public void CopyTo(EventLogEntry[] entries, int index);
        public IEnumerator GetEnumerator();
    }
}

 

반응형

EventLogEntry 클래스

 

EventLogEntry 클래스 (System.Diagnostics)

이벤트 로그에 단일 레코드를 캡슐화합니다. 이 클래스는 상속될 수 없습니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public sealed class EventLogEntry : Component, ISerializable
    {
        public int Index { get; }
        public byte[] Data { get; }
 
        public string MachineName { get; }
        public string UserName { get; }
        public string Source { get; }
        public string Category { get; }
        public short CategoryNumber { get; }
        //public int EventID { get; }
        public long InstanceId { get; }
        public EventLogEntryType EntryType { get; }
        public string Message { get; }
        public string[] ReplacementStrings { get; }
        public DateTime TimeGenerated { get; }
        public DateTime TimeWritten { get; }
 
        public bool Equals(EventLogEntry otherEntry);
    }
}

EntryWrittenEventArgs 클래스

 

EntryWrittenEventArgs 클래스 (System.Diagnostics)

EntryWritten 이벤트에 대한 데이터를 제공합니다.

learn.microsoft.com

namespace System.Diagnostics
{
    public class EntryWrittenEventArgs : EventArgs
    {
        public EntryWrittenEventArgs();
        public EntryWrittenEventArgs(EventLogEntry entry);
       
        public EventLogEntry Entry { get; }
    }
}

- EventLog 클래스를 이용하면 Trace나 Debug를 사용하지 않고 Windows 이벤트 로그에 직접 로그 기록 가능
- 이벤트 자료를 읽거나 감시하는데도 사용 가능
- Windows 서비스 응용 프로그램은 뭔가 잘못되었을 때 사용자에게 진단 정보가 기록된 파일의 위치를 알려 줄 수 없음
 * 따라서 해당 정보를 Windows 이벤트 로그에 기록하는 것이 합당
- 서비스가 문제를 일으켰다면 관리자는 일반적으로 Windows 이벤트 로그부터 점검 함
- 표준 Windows 이벤트 로그
 1. 응용 프로그램 로그: 대부분의 응용 프로그램은 응용 프로그램 로그에 로그 메시지를 기록함
 2. 시스템 로그
 3. 보안 로그

이벤트 로그 기록
- Windows 이벤트 로그에 메세지를 기록하는 과정
 1. 세 가지 표준 이벤트 로그 중 하나를 정함
 2. 로그 출처(Log Source)의 이름을 정함
 3. 표준 로그 이름, 로그 출처, 메시지 자료로 EventLog.WriteEntry를 호출
- 로그 출처
 * 이름 - 응용 프로그램에서 기록한 로그들을 쉽게 알아 볼 수 있는 문자열
 * 로그 출처의 등록 생성 - CreateEventSource
 * 로그 등록 - WriteEntry
- 로그 항목의 종류를 나타내는 EventLogEntryType 열거형에 따라 이벤트 뷰어에 표시되는 아이콘이 다름
- WriteEntry에는 로그의 범주와 이벤트 ID, 선택적인 이진 자료를 받도록 중복적재된 버전들도 있음
- CreateEventSource에는 컴퓨터의 이름을 지정할 수 있는 버전이 있음
 * 다른 컴퓨터의 이벤트 로그에 로그 메시지를 기록 할 수 있음

const string sourceName = "Seo.LogTest";
 
if (!EventLog.SourceExists(sourceName))
{
    EventLog.CreateEventSource(sourceName, "Application");
}
 
EventLog.WriteEntry(sourceName, "테스트로 로그를 기록합니다...", EventLogEntryType.Information);

이벤트 로그 읽기

- 읽고자 하는 로그의 이름으로 EventLog 클래스를 인스턴스화 (다른 컴퓨터 이름도 지정 가능)
- Entries를 통해서 각 로그 항목에 접근

EventLog log = new EventLog("Application");
 
Console.WriteLine("전체 항목 수: " + log.Entries.Count);
Console.WriteLine();
 
EventLogEntry lastLog = log.Entries[log.Entries.Count - 1];
Console.WriteLine("         Index: " + lastLog.Index);
Console.WriteLine("    InstanceId: " + lastLog.InstanceId);
Console.WriteLine("        Source: " + lastLog.Source);
Console.WriteLine("     EntryType: " + lastLog.EntryType);
Console.WriteLine("       Message: " + lastLog.Message);
Console.WriteLine("   MachineName: " + lastLog.MachineName);
Console.WriteLine("      UserName: " + lastLog.UserName);
Console.WriteLine("      Category: " + lastLog.Category);
Console.WriteLine("CategoryNumber: " + lastLog.CategoryNumber);
Console.WriteLine("   TimeWritten: " + lastLog.TimeWritten);
Console.WriteLine(" TimeGenerated: " + lastLog.TimeGenerated);
 
Console.WriteLine();
 
Console.WriteLine("ReplacementStrings: ");
foreach (var item in lastLog.ReplacementStrings)
{
    Console.WriteLine("  " + item);
}
Console.WriteLine();
 
Console.WriteLine("Press Any Key to Quit...");
Console.ReadKey(true);

- GetEventLogs를 이용하면 모든 로그를 열거할 수 있음

foreach (EventLog log in EventLog.GetEventLogs())
{
    Console.WriteLine($"{log.LogDisplayName} ({log.Entries.Count})");
}
Console.WriteLine();
 
Console.WriteLine("Press Any Key to Quit...");
Console.ReadKey(true);

이벤트 로그 감시

- EntryWritten 이벤트에 등록하면 이벤트 로그에 로그 항목이 기록 될 때마다 그 사실을 통지받을 수 있음
 1. 지역 컴퓨터의 이벤트 로그들에 대해 작동
 2. 로그를 기록한 응용 프로그램이 어떤 것인가와는 무관하게 모든 로그 항목에 대해 발동
- 로그 감시 활성화
 1. EventLog 인스턴스를 생성해서 EnablrRaisingEvent 속성을 True로 설정
 2. EntryWritten 이벤트에 대한 처리부 등록

public static void Main(string[] arg)
{
    using (var log = new EventLog("Application"))
    {
        log.EnableRaisingEvents = true;
        log.EntryWritten += DisplayEntry;
        Console.ReadLine();
    }
}
 
static void DisplayEntry(object sender, EntryWrittenEventArgs e)
{
    EventLogEntry entry = e.Entry;
    Console.WriteLine(entry.Message);
}
반응형

'C#' 카테고리의 다른 글

[C#] Task  (0) 2023.11.06
[C#] Thread  (0) 2023.11.01
[C#] Stopwatch  (0) 2023.10.30
[C#] PerformanceCounter, PerformanceCounterCategory  (0) 2023.10.28
[C#] StackTrace, StackFrame  (0) 2023.10.24
[C#] Debugger  (0) 2023.10.22
[C#] Contract, Code Contracts(코드 계약)  (0) 2023.10.20
[C#] Debug, Trace  (0) 2023.10.18