可以使用log4j。使用方法如下供参考:
导入jar包
配置log4j.properties文件
创建工具类(接口)
public interface LoggerUtil {// 得到Logger,用于打印日志
Logger logger = Logger.getLogger(LoggerUtil.class)
}
4、使用(核心代码介绍)
@RequestMapping("/delete.do")public String delete(Students students) {
try {
stuService.delete(students)
} catch (Exception e) {
// 使用日志
LoggerUtil.logger.error(e.getMessage())
}
return "redirect:selectAll.do"
}
怎么会呢... log4j多好用啊, 你先下一个log4j的jar包, 导入到项目后, 在网上找一个log4j.properties文件(必须有这个文件), 把它放到src目录下(必须), 然后需要打日志的时候logger.info("...")调用就好了啊, 没啥别的啊... 毕竟只是个日志文件, 如果你要打到文件里, 在log4j.properties文件里设置路径参数就好了, 纯手打望采纳!1.首先创建一个自定义注解拦截Controller类,代码如下/**
* 自定义注解 拦截Controller
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
String desc() default ""//标示默认打印空
}
2.创建一个打印日志的切面类,引入切面注解@Aspect,
新建方法代码如下:
// Controller层切点
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void recordLog() {
}
@Around("recordLog()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// ExPatternParser.initLogger()
long start = System.currentTimeMillis()
Object[] args = pjp.getArgs()
String remark = this.getControllerMethodDescription(pjp)
Object retVal = null
try {
retVal = pjp.proceed()
} catch (Throwable e) {
// TODO Auto-generated catch block
logger.error("请求失败" + e.toString(),e)
remark = remark + "。Exception Cause By " + e.toString()
throw e
}finally{
long end = System.currentTimeMillis()
long cost = end - start
//打印访问日志
// Controller中所有方法的参数,前两个分别为:Request,Response
if(args != null &&args.length >0){
Object o = args[0]
if(o instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) args[0]
PrintLog.visit(request, cost,remark)
}
}
}
return retVal
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
* @param joinPoint切点
* @return 方法描述
* @throws Exception
*/
public static String getControllerMethodDescription(ProceedingJoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName()
String methodName = joinPoint.getSignature().getName()
Object[] arguments = joinPoint.getArgs()
Class targetClass = Class.forName(targetName)
Method[] methods = targetClass.getMethods()
String description = ""
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes()
if (clazzs.length == arguments.length) {
ControllerLog controllerLog = method.getAnnotation(ControllerLog.class)
if(controllerLog !=null){
description =
controllerLog.desc()
}
break
}
}
}
return description
}
3.然后在每个Controller类上加上注解:
@ControllerLog(desc = "要 打印的日志内容")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)