spring boot整合log4j2及MQ消費處理系統日志示例

前言

當系統的並發比較高的時候,日志的處理輸出也是一種性能的開銷負擔,所以,選擇一個中間件來處理消費日志必不可少!

下面是spring boot整合log4j2結合spring amqp來消費處理系統日志的實例,隻需要簡單的三步

1.添加相關jar依賴

<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到處理日志的系統

<?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上下文環境中

@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

以上就是spring boot整合log4j2及MQ消費處理系統日志示例的詳細內容,更多關於spring boot整合MQ消費log4j2日志的資料請關註WalkonNet其它相關文章!

推薦閱讀: