在我们开发一个系统的时候,遇到问题总要去服务器获取日志,分析日志,这样总感觉会很麻烦,所以想想怎么方便快捷的查看系统的日志信息呢?
这边是本篇文章的初衷。日志入库,日志入库也有很多方法,这里只介绍其中一种最为简单的方法——切面日志入库
1、依赖jar包
<dependency> <groupId> org.aspectj</groupId > <artifactId> aspectjweaver</artifactId > <version> 1.8.7</version > </dependency>
2、具体切面实现类
切面实现类如何定义与实现呢?接下来我们具体分析一下代码逻辑:
首先创建切入点,注解中“ @Pointcut("execution(public * com.xxx.www.manage.controller..*.*(..))")”这部分内容是指引我们哪些包下的什么级别可以进行日志记录。
“ @Around("controllerLogInfo()")” 是定义具体的执行日志记录方法。此方法中获取了入库所需的各个参数值,然后将每个值赋值给日志对象,然后组装入库
@Aspect @Component public class LogAspect extends BaseController { private Logger logger = LoggerFactory.getLogger(LogAspect.class); @Autowired private JournalService journalService; /** * 切入点描述 这里是controller包的切入点 * 签名,可以理解成这个切入点的一个名称 */ @Pointcut("execution(public * com.xxx.www.manage.controller..*.*(..))") public void controllerLogInfo(){} @Around("controllerLogInfo()") public Object handleControllerMethodLog(ProceedingJoinPoint joinPoint) throws Throwable { long beginTime = System.currentTimeMillis(); // 获取方法签名 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); // 获取方法 Method method = methodSignature.getMethod(); //获取请求的类名 String className = joinPoint.getTarget().getClass().getName(); //获取请求的方法名 String methodName = method.getName(); //请求的参数 Object[] args = joinPoint.getArgs(); //将参数所在的数组转换成json String params = JSON.toJSONString(args,SerializerFeature.IgnoreNonFieldGetter); //获取ip地址 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西 HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest(); //获取ip地址 String ip = request.getRemoteAddr(); try { 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.getRemoteAddr(); } } catch (Exception e) { e.printStackTrace(); } User user = getUser(request); //保存日志 Journal journal = new Journal(); journal.setCreateTime(new Date()); int k = className.lastIndexOf("."); String substring = className.substring(k+1, className.length()); String nWrod = StringUtils.findNWrod(substring, 1); journal.setMethod(nWrod.toLowerCase() + "_" + methodName); journal.setName(user.getUsername()); journal.setIpAddress(ip); journal.setRemark(className + "=========" + params); Object result = null; result = joinPoint.proceed(); journalService.insertSelective(journal); return result; } }
好了,这样就轻松搞定日志入库,觉得有帮助,帮小编点个赞吧!
更多编程内容,请扫码关注《coder练习生》,如果觉得有用,也可赠送作者一杯咖啡