log4j Spring aop 注解的日志管理
本文内容纲要:log4j Spring aop 注解的日志管理
1.配置log4j配置文件
ERROR>INFO>DEBUG log4j.properties
log4j.rootLogger=INFO,stdout,logfile,db
#spring log
log4j.logger.org.springframework=ERROR
log4j.logger.com.heruan.fsmanager.base=OFF
#Console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[log]:%d{yyyy-MM-dd HH:mm:ss} 执行人ID:%X{userId},执行人:%X{userName},包名:%X{packageName},执行类:%X{className},执行方法:%X{mothedName},持续时间:%X{durTime},返回结果:%X{result},状态:%X{status},描述:%X{info} %C%l%n
#Filelogfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=${FSManagementPlatform.root}/WEB-INF/logs/system.log
log4j.appender.logfile.DatePattern = '.'yyyy-MM-dd
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[log]:%d{yyyy-MM-dd HH:mm:ss} 执行人:%X{userName},包名:%X{packageName},执行类:%X{className},执行方法:%X{mothedName},持续时间:%X{durTime},返回结果:%X{result},状态:%X{status},描述:%X{info}%n
#JDBC Appender
log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.db.BufferSize=10
log4j.appender.db.driver=com.mysql.jdbc.Driver
log4j.appender.db.URL=jdbc\:mysql\://***.***.***.***\:3306/***
log4j.appender.db.user=***
log4j.appender.db.password=*******
log4j.appender.db.layout=org.apache.log4j.PatternLayout
log4j.appender.db.sql=insert into sys_log (userId,userName,time,durTime,level,packageName,className,mothedName,result,status,info) values ('%X{userId}','%X{userName}','%d{yyyy-MM-dd HH\:mm\:ss}','%X{durTime}','%X{level}','%X{packageName}','%X{className}','%X{mothedName}','%X{result}','%X{status}','%X{info}')
写一个用户拦截器:
1 package com.heruan.fsmanage.aspect; 2
3 import java.io.IOException;
4 import javax.servlet.Filter;
5 import javax.servlet.FilterChain;
6 import javax.servlet.FilterConfig;
7 import javax.servlet.ServletException;
8 import javax.servlet.ServletRequest;
9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpSession;
12 import org.apache.log4j.MDC;
13
14 import com.heruan.fsmanage.basedevelop.utils.UniqueIdUtil;
15 import com.heruan.fsmanage.entity.basedevelop.SysUser;
16 /**
17 * @ClassName GetUserFilter
18 * @PackageName com.heruan.fsmanage.aspect
19 * @Description (得到SESSION中的用户)
20 * @author law
21 * @Date 2016-5-6 下午3:43:15
22 */
23 public class GetUserFilter implements Filter {
24
25 // 定义默认用户姓名
26 private final static String DEFAULT_USER = "guest";
27
28 public void destroy() {
29 }
30
31 public void doFilter(ServletRequest request, ServletResponse response,
32 FilterChain chain) throws IOException, ServletException {
33 HttpServletRequest req = (HttpServletRequest) request;
34 HttpSession session = req.getSession();
35 if (session == null) {
36 Long id = UniqueIdUtil.getInstanceId();
37 MDC.put("userId", id);
38 MDC.put("userName", DEFAULT_USER);
40 } else {
41 SysUser user = (SysUser) session.getAttribute("userinfo");
42 if (user == null) {
43 Long id = UniqueIdUtil.getInstanceId();
44 MDC.put("userId", id);
45 MDC.put("userName", DEFAULT_USER);
46 } else {
47 MDC.put("userId", user.getId());
48 MDC.put("userName", user.getUserName());
49 }
50 }
51
52 chain.doFilter(request, response);
53 }
54
55 public void init(FilterConfig Config) throws ServletException {
56
57 }
58 }
配置web.xml
1 <!--由Spring载入的Log4j配置文件位置--> 2 <context-param>
3 <param-name>log4jConfigLocation</param-name>
4 <param-value>classpath:new_log4j.properties</param-value>
5 </context-param>
6 <!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond-->
7 <context-param>
8 <param-name>log4jRefreshInterval</param-name>
9 <param-value>60000</param-value>
10 </context-param>
11
12 <!-- Log4jConfigListener会去log4j.propeties 读取配置文件;开一条watchdog线程每60秒扫描一下配置文件的变化 -->
13 <listener>
14 <listener-class>
15 org.springframework.web.util.Log4jConfigListener
16 </listener-class>
17 </listener>
18
19 <filter>
20 <filter-name>GetUserFilter</filter-name>
21 <filter-class>com.heruan.fsmanage.aspect.GetUserFilter</filter-class>
22 </filter>
23 <filter-mapping>
24 <filter-name>GetUserFilter</filter-name>
25 <url-pattern>/*</url-pattern>
26 </filter-mapping>
自定义注解:
package com.heruan.fsmanage.annotation;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @ClassName Action
* @PackageName com.heruan.fsmanage.annotation
* @Description 对方法信息进行描述
* @author law
* @Date 2016-5-25 下午4:23:04
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String description() default "";
}
写基于注解的切面:
package com.heruan.fsmanage.aspect;import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.heruan.fsmanage.annotation.Action;
/**
* @ClassName LogAspect
* @PackageName com.heruan.fsmanage.aspect
* @Description TODO
* @author law
* @Date 2016-5-6 上午9:56:11
*/
@Aspect
public class LogAspect {
private static Logger logger = Logger.getLogger(LogAspect.class);
@Around("doLog()")
public Object logDescp(ProceedingJoinPoint joinPoint)throws Throwable{
Object result=null;
String returnResult = "";
int durTime = -1;
String classInfo = joinPoint.getTarget().getClass().getName();
String className = classInfo.substring(classInfo.lastIndexOf(".")+1,classInfo.length());
String packageName = classInfo.substring(0,classInfo.lastIndexOf("."));
String mothedName = joinPoint.getSignature().getName();
MDC.put("className", className);
MDC.put("packageName", packageName);
MDC.put("mothedName", mothedName);
String info = getMethodDescription(joinPoint);
try{
Long startTime = System.currentTimeMillis();
result = joinPoint.proceed();
Long endTime = System.currentTimeMillis();
if(result!=null){
returnResult = result.toString().replaceAll("'", "\"");
}
durTime=(int) (endTime-startTime);
MDC.put("status", "成功");
MDC.put("durTime", durTime);
MDC.put("result", returnResult);
MDC.put("info", info);
MDC.put("level", "info");
logger.info("任务成功:"+info);
}catch(Exception e){
e.printStackTrace();
MDC.put("status", "失败");
MDC.put("durTime", durTime);
MDC.put("result", returnResult);
MDC.put("info", info);
MDC.put("level", "error");
logger.error("异常信息:"+e.getMessage(), e);
throw e;
}
return result;
}
/**
* @Title getWEBINFAddress
* @Description 获取WEB-INF路径
* @Author law
* @CreateDate 2016-5-25 下午5:28:49
* @return String
*/
private static String getWEBINFAddress() {
String url = LogAspect.class.getResource("/").getPath(); //this.getClass().getResource("/").getPath()
return url;
}
/**
* @Title getMethodDescription
* @Description 获取注解中对方法的描述信息
* @Author law
* @CreateDate 2016-5-26 下午2:36:43
* @param joinPoint
* @throws Exception
* @return 方法描述信息
*/
private static String getMethodDescription(JoinPoint joinPoint) throws Exception {
//获取实体类名
String targetName = joinPoint.getTarget().getClass().getName();
//获取方法名
String methodName = joinPoint.getSignature().getName();
//获取参数列表
Object[] arguments = joinPoint.getArgs();
//获取参数类型列表
Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
//获取拦截到的方法
Method method = joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes);
String description = "";
//获取Action注解描述信息
description = method.getAnnotation(Action.class).description();
return description;
}
}
加入一条bean:
<bean id="logAspect" class="com.heruan.fsmanage.aspect.LogAspect" />
启用aop注解代理:
<aop:aspectj-autoproxy proxy-target-class="true" />
本文内容总结:log4j Spring aop 注解的日志管理
原文链接:https://www.cnblogs.com/law-luffy/p/5533795.html
以上是 log4j Spring aop 注解的日志管理 的全部内容, 来源链接: utcz.com/z/296913.html