Springboot +AOP日志系统

Springboot +AOP日志系统_第1张图片

1、前言

一个好的日志信息整理与划分能让我们更好的定位到错误的地方,如果我们使用调试器断点机制,让问题复现,并由此定位问题并解决问题。大多时候我们遇到比较难定位的bug的时候都会这么做,如果是普通的bug相信用 System.out.println( ) 就能解决大部分的疑难杂症(狗头)。但当我们服务上线时,大量的log日志不可能直接靠在控制台里打印的来定位问题,况且你又不是一直开着你的Shell,万一关了就无了。所以成功地调试程序、监控和错误报告地关键就是日志。

2、代码部分

引入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-loggingartifactId>
dependency>

但实际开发中我们不需要添加该依赖,Spring Boot 默认的日志框架 Logback+SLF4J。而 spring-boot-starter-web已经包含了,所以我们只需要引入web组件即可

传送文献地址----

https://www.scalyr.com/blog/started-quickly-spring-boot-logging/#:~:text=Spring%20Boot%20comes%20with%20a%20preconfigured%20default%20logger,dependency%20already.%20That%E2%80%99s%20what%20we%20call%20zero-configuration%20logging.
Springboot +AOP日志系统_第2张图片

<dependency>
     <groupId>org.springframework.bootgroupId>
     <artifactId>spring-boot-starter-webartifactId>
dependency>

接下来就是对应的logback的配置了

logback-spring.xml



<configuration scan="true" scanPeriod="10 seconds">
    
    
    
    
    <contextName>logbackcontextName>
    
    <property name="log.path" value="---你想要输出日志的路径---"/>
    
    
    
    
    
    
    
    <property name="CONSOLE_LOG_PATTERN"
              value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/>
    
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFOlevel>
        filter>
        <encoder>
            <Pattern>${CONSOLE_LOG_PATTERN}Pattern>
            
            <charset>UTF-8charset>
        encoder>
    appender>
    
    
    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/log_info.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset>
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFOlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>
    
    <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/log_warn.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARNlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>
    
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/log_error.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>
    
    
    
    <springProfile name="dev">
        
        <logger name="com.*.*.mapper" level="INFO"/>
        
        <root level="INFO">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="INFO_FILE"/>
            <appender-ref ref="WARN_FILE"/>
            <appender-ref ref="ERROR_FILE"/>
        root>
    springProfile>
    
    <springProfile name="prod">
        <root level="INFO">
            <appender-ref ref="INFO_FILE"/>
            <appender-ref ref="WARN_FILE"/>
            <appender-ref ref="ERROR_FILE"/>
        root>
    springProfile>
configuration>

现在logback已经配置好了,每个对应的地方都竟可能的详细,去编写yml文件(主要的一部分),其实就是指定一下文件位置和当前环境,是测试还是生产

spring:
  profiles:
    active: dev
logging:
  config: classpath:logback-spring.xml

编写AOP

自定义编写注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLog {
     
    String value() default "";
}

重要:自定义注解的实现方法

@Aspect
@Component
public class SysLogAspect {
     
    
    @Value("${spring.application.name}")//这里的projectName自己定义的yml中配置就好
    private String projectName;

    @Resource
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.*.*.annotation.MyLog)")//这里指定你自定注解的具体位置
    public void logPointCut() {
     
    }

    @AfterReturning("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
     
        try {
     
            //这里的实体类自定义就好,更具自己的业务来定
            SysLog sysLog = new SysLog();
            //获取方法
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
      
            //方法类型
            MyLog myLog = method.getAnnotation(MyLog.class);
            String operation = myLog.value();
            sysLog.setOperation(operation);

            //方法名
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            sysLog.setMethod(className + "." + methodName);

            //方法参数
            Object[] args = joinPoint.getArgs();
            String params = Arrays.toString(args);
            sysLog.setParam(params);

            //项目名称
            sysLog.setProjectName(projectName);

		   ...........各种参数

            //ip
            String ipAddress = HttpContextUtil.getIpAddress();
            sysLog.setIp(ipAddress);

            //添加日志记录
            //这里的方法就自己去实现吧,MySQL的插入方法
            sysLogService.save(sysLog);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

这里是数据库字段,其他字段可以更具自己业务来做

Springboot +AOP日志系统_第3张图片

贴上工具类

public class HttpContextUtil {
     
    public static final String UNKNOWN = "unknown";

    public static HttpServletRequest getRequest() {
     
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest();
    }

    public static String getIpAddress() {
     
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
     
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
     
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
     
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
     
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
     
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

写个controller测试一下

 	@MyLog("测试方法")
    @ApiOperation("测试一下")
    @PostMapping(value = "/test")
    public R<Object> test(@RequestBody String info) {
     
        return RUtils.success(info);
    }	

打开测试文档输入参数

Springboot +AOP日志系统_第4张图片

再看看数据库

image-20210913195822135

再看看我们logback的输出日志的路径中是否有日志输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kNw0AOTW-1631582728451)(C:\Users\XXXLOMG\AppData\Roaming\Typora\typora-user-images\image-20210913201221289.png)]

点进info中看看,按照每日的时间来进行输出

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nyyyW6Kj-1631582728455)(C:\Users\XXXLOMG\AppData\Roaming\Typora\typora-user-images\image-20210913201309451.png)]

以上便是一个初级的日志的系统,若有以上有编写不当的地方,欢迎指正~

你可能感兴趣的:(JAVA,spring,boot,java)