Does Log4Net have anything that is comparable to Log4J Markers?

Does log4net have anything comparable to log4j Markers ?

Markers are objects that are used to add easily filtered information to log messages.

I have looked at the log4net API , but the ILog interface does not have methods that accept any additional tokens that can be interpreted as a token type of thing.

For example, I only want to register with one journal:

ILog logger = LogManager.GetLogger(typeof(MyClass));
logger.Error("This is an error!");

      

However, sometimes I want these errors to be posted to the EventLog.

I have currently created a second logger with a link to EventLogAppender. It also inherits all applications from the root registrar.

This means that I need 2 links to the registrar in the class that will register. 1 for the event log entry and 1 for the logs that I don't want to go into the event log:

ILog logger = LogManager.GetLogger(typeof(MyClass)); //root logger
ILog eventLogger = LogManager.GetLogger("EventLogger"); //eventlog logger
logger.Info("Some message that doesn't need to go to the event log.");
eventLogger.Error("Some error that does need to go to the event log.");

      

With markers, I could do something like

logger.Info(EVENT_LOG_MARKER, "This message should go to the event log.");

      

The filter will then read the token and activate the corresponding applications.

I could add a magic line to the beginning of the message and select it using a filter, but this is hackish at best.

Aside from using magic strings, is there another option in log4net to implement a Marker type system?

+3


source to share


1 answer


There ILog

are no markers in the log4net frontend , but you can use property filters to route events to the correct log: just create one logger in your code and send all events to that logger. In root config install two apps you want

root
    event log appender
    file appender

      

and then in each application, filter messages that have or don't have the correct property value, like

<!-- filter in the event log appender -->
<filter type="log4net.Filter.Property">
    <key value="ToEventLog" />
    <stringToMatch value="true" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />

      



While these are magic lines wrapped on properties instead of messages and you need to wrap your log in some code by setting a property: using IDisposable to wrap setting and debugging a property might be a good idea, something like

log.Info("To wherever!!");
using (var SendToEventLogSwitch = new EventLogSwitch)
{
    log.Info("To EventLog!!");
}

      

You can also use an extension method in ILog to add a marker and use the property mechanism behind the scenes.

public static void EventLog(this ILog log, string message)
{
    log4net.ThreadContext.Properties["ToEventLog"] = "true";
    log.Info(message);
    log4net.ThreadContext.Properties["ToEventLog"] = "false";
}

      

+3


source







All Articles