1. 程式人生 > >Springboot整合log4j2並將日誌傳送到flume

Springboot整合log4j2並將日誌傳送到flume

springboot整合log4j2大體步驟是很簡單的,只是中間有一些小細節需要注意。

首先pom檔案中增加log4j2

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

要在springboot啟動的時候就強制使用log4j2,需要排除預設的日誌:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <exclusions>
        <exclusion> 
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

然後在resource下增加log4j2的配置檔案log4j2.xml.

然後在預設配置檔案application.properties中指定一下log4j2的配置檔案:

logging.config=classpath:log4j2.xml

這裡需要注意一下,按照官方文件的說法,是會自動發現日誌的配置檔案的,在開發除錯過程中也確實是這樣。但是如果要打成war包部署到tomcat中,而且是linux下的tomcat。就會有問題,手動指定一下才會生效。如果只是打jar包通過main方法啟動是沒有問題的。

至此springboot整合log4j2就基本完成了。

然後在log4j2中配置flume

還是從pom檔案開始:

<dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-flume-ng</artifactId>
	</dependency>
    <dependency>
     <groupId>org.apache.flume</groupId>
      <artifactId>flume-ng-embedded-agent</artifactId>
      <version>1.7.0</version>
      <exclusions>
      	<exclusion>
      		<groupId>org.slf4j</groupId>
      		<artifactId>slf4j-api</artifactId>
      	</exclusion>
      	<exclusion>
      		<groupId>org.slf4j</groupId>
      		<artifactId>slf4j-log4j12</artifactId>
      	</exclusion>
      	<exclusion>
      		<groupId>log4j</groupId>
      		<artifactId>log4j</artifactId>
      	</exclusion>
      </exclusions>
    </dependency>

log4j2支援的flume是embedded模式的,所以加入flume-ng-embedded-agent

然後log4j2的配置檔案中加入flumeAppend

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [myapp] %m%n"/>
    </Console>
    <Flume name="FlumeAppender" compress="false" type="Embedded" >
      <Property name="channel.type">memory</Property>
      <Property name="channel.capacity">200</Property>
      <Property name="sinks">agent1</Property>
      <Property name="agent1.type">avro</Property>
      <Property name="agent1.hostname">192.168.0.100</Property>
      <Property name="agent1.port">44444</Property>
      <Property name="agent1.batch-size">100</Property>
      <Property name="processor.type">failover</Property>
      <PatternLayout charset="UTF-8" pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [myapp] %m%n" />
    </Flume>
  </Appenders>
  <Loggers>
    <Logger name="sysLog" level="trace">
      <AppenderRef ref="FlumeAppender"/>
    </Logger>
    <Root level="info">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

好了,結束!