【C#】イベントログ出力

■ サンプル

EventLogger.cs

using System.Diagnostics;

namespace SampleForm
{
  public static class EventLogger
  {
    private const string SourceName = "HelloWorld";
    // イベントID ★以下「使用上の注意」も参照★
    private const int DefaultEventId = 11000;
    private const int WarningEventId = 11001;
    private const int ErrorEventId = 11002;

    static EventLogger()
    {
      if (!EventLog.SourceExists(SourceName))
      {
        EventLog.CreateEventSource(SourceName, string.Empty);
      }
    }

    public static void WriteInfo(string content)
    {
      EventLogger.WriteLog(content, EventLogEntryType.Information);
    }

    public static void WriteWarning(string content)
    {
      EventLogger.WriteLog(content, EventLogEntryType.Warning);
    }

    public static void WriteError(string content)
    {
      EventLogger.WriteLog(content, EventLogEntryType.Error);
    }

    private static void WriteLog(string content, EventLogEntryType logType)
    {
      int eventId;
      switch (logType)
      {
        case EventLogEntryType.Warning:
          eventId = WarningEventId;
          break;
        case EventLogEntryType.Error:
          eventId = ErrorEventId;
          break;
        case EventLogEntryType.Information:
        default:
          eventId = ErrorEventId;
          break;
      }
      EventLog.WriteEntry(SourceName, content, logType, eventId);
    }
  }
}

使用上の注意

イベントIDの範囲について

 * イベントIDは、「0~65535(UInt16.MaxValue)」で指定すること
  => それ以外は、ArgumentExceptionが発生する
[[https://docs.microsoft.com/ja-jp/dotnet/api/system.diagnostics.eventlog.writeentry?view=netframework-4.7.2#System_Diagnostics_EventLog_WriteEntry_System_String_System_String_System_Diagnostics_EventLogEntryType_System_Int32_System_Int16_System_Byte___]]
より抜粋
~~~~~~~~
例外
ArgumentException

eventID が 0 より小さいか、MaxValue より大きいです。
~~~~~~~~