How to log FATAL (or any custom log level) with SLF4J and Log4j2

前端 未结 6 1684
粉色の甜心
粉色の甜心 2021-02-05 15:18

I have those specific requirements :

  • Need to be able to log in FATAL level
  • Need to use SLF4J<
6条回答
  •  悲哀的现实
    2021-02-05 15:25

    The only solution I've found so far is to use have 5 markers :

    final Marker traceMarker = MarkerFactory.getMarker("TRACE");
    final Marker debugMarker = MarkerFactory.getMarker("DEBUG");
    final Marker infoMarker = MarkerFactory.getMarker("INFO");
    final Marker warnMarker = MarkerFactory.getMarker("WARN");
    final Marker errorMarker = MarkerFactory.getMarker("ERROR");
    final Marker fatalMarker = MarkerFactory.getMarker("FATAL");
    

    And log passing the marker everytime :

    logger.info(infoMarker, "!!! INFO World !!!");
    logger.error(errorMarker, "!!! ERROR World !!!");
    logger.error(fatalMarker, "!!! FATAL World !!!");
    

    And modify the PatternLayout to totally remove the LogLevel and always log the Marker, such as :

    PatternLayout:
      Pattern: "%d{ISO8601_BASIC} %marker [%t] %logger{3.} - %msg%n"
    

    I kind of think this solution is a hack... It would also remove the log level of any external library using the LogLevel the right way.

    Summary : This solution isn't a good solution.

    UPDATE : I tried another solution, writing a RewritePolicy :

    public class FatalRewritePolicy implements RewritePolicy {
    
        public static final String FATAL = "FATAL";
    
        @Override
        public LogEvent rewrite(final LogEvent logEvent) {
    
            final Marker marker = logEvent.getMarker();
            if (marker == null)
                return logEvent;
    
            // Log Level is final in the LogEvent, there's no way we can modify it.
            Level level = logEvent.getLevel();
    
            return null;
        }
    }
    

    There seems to be no way to change the LogLevel of a LogEvent in Log4j2 (which make sense).

    Summary : Still no solution.

提交回复
热议问题