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

前端 未结 6 1679
粉色の甜心
粉色の甜心 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:30

    Here's the closest working solution I came with some colleagues :

    1. Create a Fatal Marker class using SLF4J Markers.
    2. Using a RoutingAppender, use the Marker as the routing pattern: "$${marker:}"
    3. Configure a Fatal-specific appender that has its own PatternLayout that doesn't include the LogLevel but a hardcoded FATAL level.

    Here's the Java sample :

    Marker fatal = MarkerFactory.getMarker("FATAL");
    // Usage example
    final Logger logger = LoggerFactory.getLogger(FatalLogger.class);
    logger.log(fatal, "this is a fatal message");
    
    // Log sample : 
    20150514T115144,279  FATAL [main] FatalLogger - this is a fatal message
    

    Here's the YAML sample :

    Configuration:
      status: debug
    
      Appenders:
        RandomAccessFile:
          - name: APPLICATION_APPENDER
            fileName: logs/application.log
            PatternLayout:
              Pattern: "%d{ISO8601_BASIC} %-5level %msg%n"
          - name: FATAL_APPENDER
            fileName: logs/application.log
            PatternLayout:
              Pattern: "%d{ISO8601_BASIC} FATAL %msg%n"
    
        Routing:
          name: ROUTING_APPENDER
          Routes:
            pattern: "$${marker:}"
            Route:
            - key: FATAL
              ref: FATAL_APPENDER
            - ref: APPLICATION_APPENDER #DefaultRoute
    
      Loggers:
        Root:
          level: trace
          AppenderRef:
            - ref: ROUTING_APPENDER
    

提交回复
热议问题