转载请联系JAVA日知录公众号。概述在单个项目中,如果我们需要记录操作日志,一般会通过以下方式实现:创建自定义注解,标记业务操作类型,通过AOP组装日志实体,完成日志的收集。具体实现可以参考以下文章链接:http://javadaily.cn/articles/2020/05/13/1589330750429.html但是在微服务架构中,我们不可能为每个服务都写一个自定义的注解,然后写一个AOP,这显然违背了Don'tRepeatyourself精神。所以这时候我们一般会创建一个公共组件,在公共组件中完成日志的收集,后端服务只需要引入这个公共组件即可。这就是今天文章的内容,一个独立的业务日志采集组件。SpringBootStarter要实现以上功能,我们需要使用SpringBootStarter来实现。SpringBoot的一大优势是Starter。通过Starter,我们可以封装公共的业务逻辑和参数初始化。如果你是开发微服务,Starter的编写是必须的。掌握。这里简单提一下SpringBootStarter实现自动配置的过程。spring-boot启动时会在starterjar包中找到resources/META-INF/spring.factories文件,根据spring.factories文件中的配置找到需要自动配置的类。,xxxAutoConfigure通过xxxAutoConfigure上的注解@EnableConfigurationProperties将当前模块的属性绑定到“Environment”(如果有的话)。xxxAutoConfigure中定义的bean自动组装到IOC容器中。实战过程如下:首先,我们在项目中创建启动模块,如cloud-component-logging-starter,将配置类SysLogAutoConfigure@ConfigurationpublicclassSysLogAutoConfigure{@BeanpublicSysLogAspectcontrollerLogAspect(){returnnewSysLogAspect();}}写在SysLogAutoConfigure,我们注入一个日志切面SysLogAspect,由于日志采集工具不需要额外的配置属性,所以我们不需要定义属性配置类。自定义日志注解SysLog@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceSysLog{/***日志内容*@return{String}*/Stringvalue();}自定义日志切面SysLogAspect@AspectpublicclassSysLogAspect{privatefinalLoggerlog=LoggerFactory.getLogger(this.getClass());@Pointcut("@annotation(com.javadaily.component.logging.annotation.SysLog)")publicvoidlogPointCut(){}@Around("logPointCut()")publicObjectaround(ProceedingJoinPointpjp)throwsThrowable{MethodSignaturesignature=(MethodSignature)pjp.getSignature();Methodmethod=signature.getMethod();//类名StringclassName=pjp.getTarget().getClass().getName();//方法名StringmethodName=signature.getName();SysLogsyslog=method.getAnnotation(SysLog.class);//操作Stringoperator=syslog.value();longbeginTime=System.currentTimeMillis();ObjectreturnValue=null;Exceptionex=null;try{returnValue=pjp.proceed();returnreturnValue;}catch(Exceptione){ex=e;throwe;}finally{longcost=System.currentTimeMillis()-beginTime;if(ex!=null){log.error("[类:{}][方法:{}][运算符:{}][成本:{}毫秒][参数:{}][发生异常]",className,methodName,operator,pjp.getArgs(),ex);}else{log.info("[类:{}][方法:{}][运算符:{}][成本:{}毫秒][参数:{}][return:{}]",className,methodName,operator,cost,pjp.getArgs(),returnValue);}}}}上面的部分表示使用@SysLog注解的方法自动收集日志。输入日志到日志文件在resource/META-INF目录下创建spring.factories文件,加载配置类SysLogAutoConfigureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.javadaily.component.logging.configure.SysLogAutoConfigure在微服务中引入日志组件
