Bunjy
Bunjy

Reputation: 130

Is EventLog writer threadsafe

I'm just looking for confirmation that this implementation is thread-safe. I can't find any info on whether the static .Net EventLog.WriteEntry method that I use in my WriteLog method internally thread-safe.

The context within which I need it to be thread-safe is this. I have 3 threads I want them to share same logwriter instance. They will all write to the same event log Source - the source can't be changed.

There are no member variables in the class to get out of sync from different threads accessing them, so I'm thinking the answer to whether it is threadsafe lies purely on whether the EventLog.WriteEntry method is itself threadsafe.

I'd appreciate if someone can confirm this. Many thanks.

public class EventLogWriter : ILogWriter
{
    private string EventLogSourceName;
    public EventLogWriter() { EventLogSourceName = System.Configuration.ConfigurationManager.AppSettings["CustomEventLogSourceName"]; }
    public EventLogWriter(string eventLogSourceName) { EventLogSourceName = eventLogSourceName; }

    // ILogWriter interface method
    public void WriteLog(string content, LogType logType)
    {
        // maps from our logType to the event log type
        EventLogEntryType eventLogType = GetEventLogType(logType);
        EventLog.WriteEntry(this.EventLogSourceName, content.ToString(), eventLogType, 0, (short)logType);
    }

    protected EventLogEntryType GetEventLogType(LogType logType)
    {
        EventLogEntryType eventLogType;
        switch (logType)
        {
            case LogType.UnhandledException:
                eventLogType = EventLogEntryType.Error;
                break;
            case LogType.HandledException:
                eventLogType = EventLogEntryType.Warning;
                break;
            case LogType.Warning:
                eventLogType = EventLogEntryType.Warning;
                break;
            case LogType.Information:
                eventLogType = EventLogEntryType.Information;
                break;
            case LogType.Verbose:
                eventLogType = EventLogEntryType.Information;
                break;
            default:
                eventLogType = EventLogEntryType.Error;
                break;
        }
        return eventLogType;
    }
}

Upvotes: 3

Views: 1481

Answers (1)

RogerN
RogerN

Reputation: 3821

If you read the documentation of the EventLog class, you'll find this note at the bottom:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Upvotes: 2

Related Questions