title: 自定义log4j2发送日志到Kafka
tags: log4j2,kafka
为了给公司的大数据平台提供各项目组的日志,而又使各项目组在改动上无感知。做了一番调研后才发现log4j2默认有支持将日志发送到kafka的功能,惊喜之下赶紧看了下log4j对其的实现源码!发现默认的实现是同步阻塞的,如果kafka服务一旦挂掉会阻塞正常服务的日志打印,为此本人在参考源码的基础上做了一些修改。
log4j日志工作流程
log4j2对于log4j在性能上有着显著的提升,这点官方上已经有了明确的说明和测试,所以不多赘述。在为了更熟练的使用,还是有必要了解其内部的工作流程。这是 官网 log4j的一张类图
Applications using the Log4j 2 API will request a Logger with a specific name from the LogManager. The LogManager will locate the appropriate LoggerContext and then obtain the Logger from it. If the Logger must be created it will be associated with the LoggerConfig that contains either a) the same name as the Logger, b) the name of a parent package, or c) the root LoggerConfig. LoggerConfig objects are created from Logger declarations in the configuration. The LoggerConfig is associated with the Appenders that actually deliver the LogEvents.
官网已经解释他们之间的关系了,这里不再对每个类的功能和作用做具体介绍,今天的重点是 Appender 类,因为他将决定将日志输出至何方。
- Appender
The ability to selectively enable or disable logging requests based on their logger is