Skip to main content

C# Windows Event Log Helper.

using System.Diagnostics;

internal static class WindowsEventLogger
{
    private const string windowsEventLogName = "Application";
    private const string eventLogSourceName = "MyService";

    public static void Create()
    {
        if (!EventLog.SourceExists(eventLogSourceName, "."))
        {
            EventLog.CreateEventSource(
                eventLogSourceName,
                windowsEventLogName);
        }
    }

    public static void Delete()
    {
        if (EventLog.SourceExists(eventLogSourceName, "."))
        {
            EventLog.DeleteEventSource(eventLogSourceName, ".");
        }
    }

    public static void Log(string message, 
        EventLogEntryType type = EventLogEntryType.Information)
    {
        EventLog.WriteEntry(
            eventLogSourceName,
            message,
            type
        );
    }

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

    public static void LogWarning(string message)
    {
        Log(message, EventLogEntryType.Warning);
    }
}