技术交流:springboot配置阿里云日志服务与log4j2 lookup

本文介绍如何在SpringBoot应用中配置阿里云日志服务,包括application.yml配置、log4j2.xml示例及启动类事件监听的实现。

阿里云日志服务

文档:https://help.aliyun.com/product/28958.html

材料准备:project、logstore、accessKeyId、accessKeySecret、endpoint

配置application.yml

将准备好的accessKeyId、accessKeySecret配置到application.yml
在这里插入图片描述

配置log4j2.xml

在这里插入图片描述
代码示例:


<Appenders>
	<Loghub name="Loghub"
	      project="ow-sys"
	      logstore="app_log"
	      accessKeyId="${sys:aliyun.log.accessKeyId}"
	      accessKeySecret="${sys:aliyun.log.accessKeySecret}"
	      endpoint="cn-hangzhou.log.aliyuncs.com"
	      totalSizeInBytes="104857600"
	      maxBlockMs="0"
	      batchSizeThresholdInBytes="524288"
	      batchCountThreshold="4096"
	      lingerMs="2000"
	      retries="3"
	      baseRetryBackoffMs="100"
	      topic="dev"
	      timeFormat="yyyy-MM-dd HH:mm:ss"
	      timeZone="UTC">
	      <PatternLayout pattern="%d %-5level [%thread] %logger{0}: %msg"/>
	    </Loghub>
	<Loggers>
	    <AsyncLogger name="xxx" level="WARN" includeLocation="true">
	      <AppenderRef ref="Loghub"/>
	    </AsyncLogger>
	</Loggers>
</Appenders>

配置springboot启动程序

1.创建事件监听类

public class LoggingListener implements ApplicationListener, Ordered {

    @Override
    public int getOrder() {
        return LoggingApplicationListener.DEFAULT_ORDER - 1;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) event)
                .getEnvironment();

            String accessKeyId = Optional.ofNullable(environment.getProperty("aliyun.log.accessKeyId"))
                               .orElse("");
            String accessKeySecret = Optional.ofNullable(environment.getProperty("aliyun.log.accessKeySecret"))
                                         .orElse("");
            System.setProperty("aliyun.log.accessKeyId", accessKeyId);
            System.setProperty("aliyun.log.accessKeySecret", accessKeySecret);
        }
    }
}
  1. 添加到SpringApplication
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(MyApplication.class);
        application.addListeners(new LoggingListener());
        application.run(args);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值