微服务下日志处理组件

与传统单体应用不同,微服务下由于,项目模块、业务拆分成多个独立系统,数据库一般也相互独立。所以对于日志的统一管理和收集,也趋于复杂,这里提供一种通用思路借助于springboot自动配置和spring事件发布订阅、SpringAop以及组件化思想,构建一个通用日志组件

实现思路与步骤

1.通过自定义注解@ZgLog携带项目模块名和日志操作类型
/**
 * @author haopeng
 * @date 2019-06-09 17:42
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZgLog {

    /**
     * 服务(子系统)名 默认取${spring.application.name}
     */
    String serverName() default "";

    /**
     * 模块名
     */
    String module() default "";

    /**
     * 日志描述信息
     */
    String description() default "";
}
2.通过Apo Aspect拦截所有配置@ZgLog的业务请求
/**
 * @author haopeng
 * @date 2019-06-09 17:47
 */
@Aspect
public class LogAspect {

    @Value("${spring.application.name}")
    private String serverName;

    @Around(value = "@annotation(zgLog)")
    public Object around(ProceedingJoinPoint point, ZgLog zgLog) throws Throwable {
        Logger logger = LoggerFactory.getLogger(LogAspect.class);
        String strClassName = point.getTarget().getClass().getName();
        String strMethodName = point.getSignature().getName();
        logger.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);
        SysLog logVo = SysLogUtils.getSysLog();
        logVo.setServerName(StringUtils.isNotBlank(zgLog.serverName()) ? zgLog.serverName() : serverName);
        logVo.setModule(zgLog.module());
        logVo.setDescription(zgLog.description());
        // 发送异步日志事件
        Long startTime = System.currentTimeMillis();
        Object obj = point.proceed();
        Long endTime = System.currentTimeMillis();
        logVo.setTime(endTime - startTime);
        SpringContextHolder.publishEvent(new SysLogEvent(logVo));
        return obj;
    }
}

上面spring.application.name取自微服务中服务名称,用于@ZgLog注解中默认子系统名称,因为统一子系统名称相同,重复配置很臃肿。

另外,拦截到的日志信息通过publishEventSpring事件发布功能进行日志消费

3.定义日志事件类

只需集成Spring ApplicationEvent即可作为事件进行发布

public class SysLogEvent extends ApplicationEvent {

    public SysLogEvent(SysLog source) {
        super(source);
    }
}
4.在SpringContextHolder工具类中定义事件发布方法
    @Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static  T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static  T getBean(Class requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        if (logger.isDebugEnabled()){
            logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static  String getStatic(){
        return SpringContextHolder.getApplicationContext().getApplicationName()+ "/static";
    }
    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * 检查ApplicationContext不为空.
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }

    /**
     * 发布事件
     *
     * @param event
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }

}

如上:publishEvent方法,用于发布日志消费(入库)事件

5.定义事件监听器

事件发布后,必须也要有事件的监听消费,一一对应,类似消息队列JMS规范中的点对点事件模型

/**
 * @author haopeng
 * @date 2019-06-09 18:13
 */
public class SysLogListener {

    private static final Logger logger = LoggerFactory.getLogger(SysLogListener.class);

    private RemoteLogService remoteLogService;

    @Async
    @Order
    @EventListener
    public void saveSysLog(SysLogEvent event) {
        SysLog sysLog = (SysLog) event.getSource();
        logger.info("日志信息...");
        //todo insert logs into mysql ...
        remoteLogService.saveLog(sysLog);
    }

    public RemoteLogService getRemoteLogService() {
        return remoteLogService;
    }

    public void setRemoteLogService(RemoteLogService remoteLogService) {
        this.remoteLogService = remoteLogService;
    }

    public SysLogListener(RemoteLogService remoteLogService) {
        this.remoteLogService = remoteLogService;
    }
}

6.日志统一消费入库

日志的展示聚合一般在项目平台应用模块,所以这里采用feign组件统一保存日志

@FeignClient(value = "fire-ww-01", fallbackFactory = RemoteLogServiceFallbackFactory.class)
public interface RemoteLogService {

    /**
     * 保存日志
     * @param sysLog log
     * @return boolean
     */
    @PostMapping("/log")
    boolean saveLog(@RequestBody SysLog sysLog);
}

其中RemoteLogServiceFallbackFactory为日志调用feigin熔断器,具体代码如下:

/**
 * @author haopeng
 * @date 2019-06-09 18:17
 */
@Component
public class RemoteLogServiceFallbackImpl implements RemoteLogService {

    private static final Logger LOG = LoggerFactory.getLogger(RemoteLogServiceFallbackImpl.class);
    private Throwable cause;

    @Override
    public boolean saveLog(SysLog sysLog) {
        LOG.error("feign 插入日志失败", cause);
        return false;
    }

    public Throwable getCause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }
}

7.在平台模块实现日志的写入和保存

这里的代码不再赘述根据自己项目的技术栈实现rest接口实现即可

8.组件化,自动化,开关化
  • 通过SpringBoot自动配置实现零配置
    在日志组件中穿件resources/META-INF/spring.factories文件(该文件是springboot自动配置读取文件)SpringBoot在启动时会根据此类文件自动加载相关配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zg.common.log.LogAutoConfiguration
  • LogAutoConfiguration自动配置类实现
@EnableAsync
@Configuration
@ConditionalOnWebApplication
@ConditionalOnProperty(name = "enable",prefix = "zg.log",havingValue = "true",matchIfMissing = true)
@EnableFeignClients({"com.zg.common.log.feign"})
public class LogAutoConfiguration {

    private final RemoteLogService remoteLogService;

    @Bean
    public SysLogListener sysLogListener() {
        return new SysLogListener(remoteLogService);
    }

    @Bean
    public LogAspect logAspect() {
        return new LogAspect();
    }

    public LogAutoConfiguration(RemoteLogService remoteLogService) {
        this.remoteLogService = remoteLogService;
    }
}

说明:

  1. @EnableAsync开启异步功能
  2. @Configuration声明配置类
  3. @ConditionalOnWebApplication只有web项目应用该组件时才会加载该配置
  4. @EnableFeignClients声明feign客户端以及组件包扫描路径
  • 通过自定义属性灵活控制日志开关
    上面LogAutoConfiguration日志自动配置类中@ConditionalOnProperty(name = "enable",prefix = "zg.log",havingValue = "true",matchIfMissing = true)
    通过加载项目中zg.log.enable的值来决定是否加载该配置,为true时加载,默认true

例如,在项目配置文件中通过如下定义来开启/关闭日志功能

zg:
  log:
    enable: false/false

以上就是微服务中日志处理的一种常见思路,到此项目中可以完成日志的统一入库与展示

拓展---组件化

以上示例是在项目的公共依赖模块中,如common中定义,那么依赖该公共组件的项目就可实现日志的处理,如果别的项目也需要用,是不是在写一遍逻辑,其实可以利用mavne去抽离成公共日志组件

  1. 新建java maven工程,引入相关基础依赖,实现以上逻辑。
  2. 打包jar文件
  3. 安装jar文件到本地仓库或者maven私服
    执行maven部署命令
mvn install:install-file -Dfile=D:/lib/com.zg.log.jar -DgroupId=com.zg -DartifactId=fire-log -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true
  1. 任意项目模块中引入
    
                com.zg
                fire-log
                1.0
            

由于引入的公共日志组件,所以日志组件的自动配置文件spring.factories也会自动加载,其实这也是为什么我们在引入SpringBoot的一些starter后可以零配置进行一些功能集成,例如spring-data-redis,其实也就是这个原理

你可能感兴趣的:(微服务下日志处理组件)