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

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

    Here is what I did for log4j which I also recommend for log4j2....

    Write your own custom slf4j static binder aka bridge. This requires a little work but is well worth it for a variety of complicated reasons 1 that I will blog about one day.

    Here is what you do.

    1. You copy this code here: https://github.com/apache/logging-log4j2/tree/master/log4j-slf4j-impl
    2. You then want to edit the Log4jLogger class and change the marker methods (trace,error,warn,info, etc) to dispatch appropriately. ie if (marker.contains("FATAL")) fatal(....);
    3. Exclude the original log4j-slf4j-impl from your project and use your new code in place.

    I honestly think slf4j is severely flawed because

    • it makes it very difficult/impossible to override hardcore static initialization along with also not providing logger.fatal(...).
    • Markers are not needed and are inherently complex:
      • Very very very few projects use markers. I actually looked/grepped open source projects and marker usage is close to zero low.
      • The ones that use marker are because fatal is missing. It is not 80/20. Markers are for the 1% and fatal is for the 99%.
      • Many developers think that somehow using the marker "fatal" will map it to fatal.
      • Few know what a detached marker is including myself.
      • There is overlap with what the MDC context provides. Given event dimension oriented databases (elasticsearch, druid, etc) the MDC context is superior (name/value pair).

    1 one of them being able to actually be part of the boot process of your logging framework opposed to hard to determine almost arbitrary static initialization

提交回复
热议问题