您的位置:首页 > 编程语言 > Java开发

【JAVA笔记——器】Spring Aop 实现Log日志系统——基本实现

2016-09-07 23:10 501 查看
Log日志系统可以说是项目开发中最基本的模块之一,在未使用Spring Aop之前,日志记录都是采用手工配置。由于开发人员的代码风格不统一,经常会导致日志风格混乱,难以阅读,甚至日志遗漏情况。

通过Aop可以实现日志系统的自动配置,减少人工配置的错误风险,同时提高日志系统的健壮性。

基本配置

xmlns:context=”http://www.springframework.org/schema/context”

xmlns:aop=”http://www.springframework.org/schema/aop”

xmlns:task=”http://www.springframework.org/schema/task”

<!-- 容器配置 -->
<context:component-scan base-package="com.cunchen.aop.common"/>
<!-- 上下文 注解 -->
<context:annotation-config/>
<!-- 注解自动代理 -->
<aop:aspectj-autoproxy/>


代码实现

aop配置不明白的地方,可以参照【JAVA笔记——器】Spring面向切面编程 Aspect Oriented Programming with Spring

/**
* 日志切面
* @author cunchen
* 2016年9月7日下午11:03:08
*/
@Aspect
@Component
public class LogAspect {

/**
* 环绕通知
* 匹配所有com.cunchen.*.service service方法且只有一个参数
* @param pjp
* @param param
* @return
* @throws Throwable
*/
@Around("execution(* com.cunchen.*.service.*.*(..)) && args(param)")
public Object doBasicProfiling(ProceedingJoinPoint pjp, Object param) throws Throwable {
LogFileWriter writer = new LogFileWriter();
writer.outputLog(pjp.getSignature().toLongString() + "\t time = " + System.currentTimeMillis());
Object retVal = pjp.proceed(new Object[]{param});
if(retVal != null)
writer.outputLog("result = " + retVal.toString() + "\t time = " + System.currentTimeMillis());
else
writer.outputLog("spend time = " + System.currentTimeMillis());
return retVal;
}
}

**
* Log文件输出
* @author cunchen
* 2016年9月7日下午2:40:26
*/
public class LogFileWriter {

public boolean outputLog(String log) {
URL url = ClassLoader.getSystemResource("");
System.out.println("\nurl = " + url + "\n");
File f = new File(url.getFile() + "test.log");
BufferedWriter writer = null;
try {
if(!f.isFile()) {
f.getParentFile().mkdirs();
f.createNewFile();
} else {
writer = new BufferedWriter(new FileWriter(f, true));
writer.append(log + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: