首頁 > 軟體

spring boot整合log4j2及MQ消費處理系統紀錄檔範例

2022-03-05 19:00:31

前言

當系統的並行比較高的時候,紀錄檔的處理輸出也是一種效能的開銷負擔,所以,選擇一箇中介軟體來處理消費紀錄檔必不可少!

下面是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紀錄檔的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com