Home  >  Q&A  >  body text

log4j - java的日志到底是怎么一回事

黄舟黄舟2714 days ago492

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-17 16:57:57

    First, you need to understand a design pattern: the adapter pattern.

    There are many libraries used by Java to record logs, such as Logger, Log4j, and Logback that come with the JDK. They are incompatible with each other. Normally, we just choose one of them when writing code.

    However, if one day the code you wrote is open sourced and wants to be used by others, then the question arises, which logging library should be used? Of course, you can't just choose one, because you don't know which logging framework is used by people who use your open source library. At this time, if you want to be compatible with whichever logging framework others use, you should use commons-logging or slf4j. Therefore, generally open source frameworks do not use specific logging frameworks, but use commons-logging or slf4j to process logs. This way, logs can be recorded according to the specific logging framework used by the user. For example, Hibernate uses slf4j (but it seems that the latest version uses is the JBOSS adapter), and Spring uses commons-logging.

    Java is different from JDBC in terms of logging. JDBC has a common set of standard APIs. Whether you connect to Oracle or MySQL, the API interface is the same. However, the log libraries JDK Logger, Log4j, and Logback are incompatible with each other and have no common interface. Therefore, commons-logging and slf4j abstract a common interface through the adapter pattern, and then implement logging according to the specific logging framework used.

    To summarize, JDK Logger, Log4j, and Logback are the implementation of specific logging frameworks, while commons-logging and slf4j are abstract adapter interfaces to solve the incompatibility between log frameworks.

    Finally, this blog is my source code analysis of slf4j. I hope it will be helpful to you: http://blog.csdn.net/xiao__gui/article/details/32695647

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 16:57:57

    Some are interfaces and some are implementations. slf4j is an upgraded version of log4j and both implements commons-logging.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 16:57:57

    slf4j is a log facade. You can choose to use commons-logging, log4j, logback and other specific implementations at the bottom layer.

    reply
    0
  • Cancelreply