c# - How to know if log4net has logged an error -
i use log4net in console application, use log.error("message log");
multiple times in if/else structures.
application has return code specifies if error has occurred during run of application (0 → ok, 1 → @ least 1 error occurred).
there way ask log4net if logged error, instance:
bool b = logmanager.atleastoneerrorhasbeenlogged;
this seems straightforward if use custom appender purpose track if error occurred.
this (untested) example uses technique of calling appender if log level error using levelrangefilter
check log level (or other criteria) in append method, or in root logger config. example assumes using xml config rather programmatic config, possible add appenders programatically used loggers.
the appender:
public namespace myapp { public class errorflagappender : appenderskeleton { public bool erroroccurred { get; set; } protected override void append(loggingevent loggingevent) { erroroccurred = true; } } }
the config:
<appender name="errorflagappender" type="myapp.errorflagappender,myapp" > <filter type="log4net.filter.levelrangefilter"> <levelmin value="error"/> <levelmax value="error"/> </filter> </appender> <root> <appender-ref ref="[your existingappender]" /> <appender-ref ref="errorflagappender" /> </root>
then can have extension method see if error occurred:
public static class logmanagerextensions { public static bool atleastoneerrorhasbeenlogged(this logmanager logmanager) { var flagappenders = logmanager.getrepository() .getappenders() .oftype<errorflagappender>(); return flagappenders.any(f => f. erroroccurred); } }
Comments
Post a Comment