EventLog instance versus static methods - preference?

When writing to the event log, I can create an instance of EventLog, hold it as a member variable and call WriteEntry (string message) on it every time I want to register a message.

Alternatively, I can simply call the static version: EventLog.WriteEntry (string source, string message).

Should I prefer one alternative to another?

In my current situation, I intend to create my own journal with one or two sources.

+4
source share
2 answers

If you are writing a test test or module checking your code, using a static class is not recommended.

I would bind an EventLog in a class that implements the common ILog interface. You can enter this class or create it in each class that uses it. This should give you better flexibility in the future if you need to replace EventLog with some other way of logging.

Interface example:

public interface ILog { void Info(string format, params object[] args); void Warn(string format, params object[] args); void Error(Exception exception); } 

You can expand or modify this to create a contract that makes sense to you.

+6
source

You better implement the Singleton pattern for this case.

 class Logger { private static Logger log = null; private void Logger() { setLevel(Logger.INFO); } public static Logger getLog() { if (log == null) { log = new Logger(); } return log; } } 
+1
source

Source: https://habr.com/ru/post/1381785/


All Articles