前言碎语
当系统的并发比较高的时候,日志的处理输出也是一种性能的开销负担,所以,选择一个中间件来处理消费日志必不可少!下面是spring boot整合log4j2结合spring amqp来消费处理系统日志的实例,只需要简单的三步
1.添加相关jar依赖
代码语言:javascript复制 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
2.系统log4j2.xml配置,如果需要跨系统处理日志,拷贝一份log4j2.xml到处理日志的系统
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%m%n" />
</Console>
<RabbitMQ name="rabbitmq"
addresses="localhost:5672"
user="guest"
password="guest"
virtualHost="/"
exchange="log4j2Sample"
applicationId="log4j2SampleAppId"
routingKeyPattern="%X{applicationId}.%c.%p"
contentType="text/plain"
contentEncoding="UTF-8"
generateId="false"
deliveryMode="PERSISTENT"
charset="UTF-8"
senderPoolSize="3"
maxSenderRetries="5">
</RabbitMQ>
</Appenders>
<Loggers>
<Logger name="org.springframework.amqp.samples.log4j2" level="info">
<AppenderRef ref="rabbitmq" />
</Logger>
<Root>
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>
3.添加处理日志的消息监听,请将以下代码置于spring context上下文环境中
代码语言:javascript复制 @RabbitListener(bindings = @QueueBinding(
exchange = @Exchange(value = "log4j2Sample", type = ExchangeTypes.FANOUT),
value = @org.springframework.amqp.rabbit.annotation.Queue))
public void echoLogs(String logMessage) {
System.out.println("在这里处理消费你的日志信息" logMessage);
}
更多spring amqp的应用,请参考spring amqp官方参考文档:http://docs.spring.io/spring-amqp/docs