原创

SpringBoot项目实战(6):整合Log4j和Aop,实现简单的日志记录

目录结构

flyat 文章图片

1.pom.xml

<!--log4j2-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- aop -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="com.sbm" level="trace" additivity="false">
            <AppenderRef ref="Console" />
        </Logger>
        <Root level="error">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

3.Aop记录Log类:AppLogAspect

package com.sbm.aspects;
import com.sbm.util.IPUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
/**
 * sbm
 * Created by yadong.zhang on com.sbm.aspects
 * User:yadong.zhang
 * Date:2016/10/21
 * Time:15:53
 */
@Component
@Aspect
/*
 * 定义切面执行的优先级,数字越低,优先级越高
 * 在切入点之前执行:按order值有小到大的顺序执行
 * 在切入点之后执行:按order值由大到小的顺序执行
 */
@Order(-5)
public class AppLogAspect {
    private Logger logger = LogManager.getLogger(AppLogAspect.class);
    // 保证每个线程都有一个单独的实例
    private ThreadLocal<Long> time = new ThreadLocal<>();
    @Pointcut("execution(* com.sbm.controller..*.*(..))")
    public void pointcut() {
    }
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        time.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求的内容
        logger.info("Request URL: " + request.getRequestURL().toString());
        logger.info("Request Method: " + request.getMethod());
        String ip = request.getRemoteAddr();
        if (ip.indexOf(":0") > -1) {
            ip = IPUtil.getRealIp();
        }
        logger.info("IP: " + ip);
        logger.info("User-Agent: " + request.getHeader("User-Agent"));
        logger.info("Class Method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("Cookies: " + request.getCookies());
        logger.info("Params: " + Arrays.toString(joinPoint.getArgs()));
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String paraName = enums.nextElement();
            logger.info(paraName + ":" + request.getParameter(paraName));
        }
    }
    @AfterReturning("pointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        logger.info("耗时 : " + ((System.currentTimeMillis() - time.get())) + "ms");
        logger.info("AppLogAspect.doAfterReturning()");
    }
}

4.简单的controller请求

@RequestMapping("/message/{currentPage}")
 public String message(@PathVariable("currentPage") Integer currentPage, Model model){
     if(currentPage!= null){
         PageHelper.startPage(currentPage, 11);
     }
     LOGGER.debug("程序执行的时候输出Log日志...");
     List<Message> messages = messageService.list();
     model.addAttribute("messages", messages);
     return "message";
 }

5.IPUtil工具类

package com.sbm.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
 * sbm
 * Created by yadong.zhang on com.sbm.util
 * User:yadong.zhang
 * Date:2016/10/21
 * Time:16:04
 */
public class IPUtil {
    public static String getRealIp() {
        String realIp = null;
        InetAddress ip = null;
        try {
            if (isWindowsOS()) { // windows
                ip = InetAddress.getLocalHost();
            } else { // Linux ,从网卡中获取ip地址
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces =
                        (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
                NetworkInterface ni = null;
                Enumeration<InetAddress> ips = null;
                while (netInterfaces.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    ni = (NetworkInterface) netInterfaces.nextElement();
                    ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = (InetAddress) ips.nextElement();
                        if (ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()  
                                && ip.getHostAddress().indexOf(":") == -1) {
                            bFindIP = true;
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ip != null) {
            realIp = ip.getHostAddress();
        }
        return realIp;
    }
    /**
     * 判断当前系统类型
     *
     * @return
     */
    private static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }
}

6.效果

flyat 文章图片


其他相关文章


正文到此结束