java web 开发日志管理
- 核心工具类 LogAopAction.java(切口类)
@Aspect
public class LogAopAction {
//注入初始化service
private InitServiceImp initServiceImp;
public void setInitServiceImp(InitServiceImp initserviceimp){
this.initServiceImp = initserviceimp;
}
public InitServiceImp getInitServiceImp(){
return this.initServiceImp;
}
//开始时间
private long BEGIN_TIME ;
//结束时间
private long END_TIME;
//运行日志
private Log log = new Log();
//切入点控制在controller层
@Pointcut("execution(* com.hzyc.registerSystem.controller..*.*(..))")
private void controllerAspect(){}
/**
* 方法执行前操作:记录开始执行时间
*/
@Before("controllerAspect()")
public void doBefore(){
BEGIN_TIME = new Date().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
sdf.format(new Date(BEGIN_TIME));
System.out.println("方法开始执行.."+ sdf.format(new Date(BEGIN_TIME)));
}
/**
* 方法执行后操作:记录结束执行时间
*/
@After("controllerAspect()")
public void after(){
END_TIME = new Date().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
System.out.println("方法结束执行.."+sdf.format(new Date(BEGIN_TIME)));
}
/**
* 方法return结束后操作:记录日志
*/
@AfterReturning("controllerAspect()")
public void doAfter(){
System.out.println(END_TIME-BEGIN_TIME);
try {
//request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8");
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
log.setActiontime(String.valueOf(END_TIME-BEGIN_TIME));
log.setGmtcreate(sdf.format(new Date(BEGIN_TIME)));
System.out.println(log.getLoginip()+"日志信息2"+log.toString());
LogAopAction laa = (LogAopAction)BeanUtil.getBean("logAop");
if(log.getState()==1){
System.out.println("执行成功记录信息");
laa.getInitServiceImp().insertLog(log);
}else if(log.getState()==-1){
System.out.println("执行失败记录信息");
laa.getInitServiceImp().insertLog(log);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 抛出异常操作
*/
@AfterThrowing("controllerAspect()")
public void doAfterThrow(){
System.out.println("方法执行失败-----------------------------------");
}
/**
* 方法执行
* @param pjp
* @return
* @throws Throwable
*/
@Around("controllerAspect()")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
//日志实体对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取当前登陆用户信息
Users us =(Users)request.getSession().getAttribute("user");
System.out.println("用户信息"+us);
if(us != null){
log.setLoginaccount(us.getName());
}else{
log.setLoginaccount("null");;
}
// 拦截的实体类,就是当前正在执行的controller
Object target = pjp.getTarget();
// 拦截的方法名称。当前正在执行的方法
String methodName = pjp.getSignature().getName();
// 拦截的方法参数
Object[] args = pjp.getArgs();
// 拦截的放参数类型
Signature sig = pjp.getSignature();
MethodSignature msig = null;
if (!(sig instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
msig = (MethodSignature) sig;
Class[] parameterTypes = msig.getMethod().getParameterTypes();
Object object = null;
Method method = null;
try {
method = target.getClass().getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (null != method) {
// 判断是否包含自定义的注解,说明一下这里的SystemLog就是我自己自定义的注解
if (method.isAnnotationPresent(SystemLog.class)) {
SystemLog systemlog = method.getAnnotation(SystemLog.class);
log.setModule(systemlog.module());
log.setMethod(systemlog.methods());
log.setLoginip(getIp(request));
log.setActionurl(request.getRequestURI());
try {
object = pjp.proceed();
log.setDescription("执行成功");
log.setState((short) 1);
} catch (Throwable e) {
// TODO Auto-generated catch block
log.setDescription("执行失败");
log.setState((short)-1);
}
} else {//没有包含注解
object = pjp.proceed();
//log.setDescription("此操作不包含注解");
log.setState((short)0);
}
} else { //不需要拦截直接执行
object = pjp.proceed();
//log.setDescription("不需要拦截直接执行");
log.setState((short)0);
}
return object;
}
/**
* 获取ip地址
* @param request
* @return
*/
private String getIp(HttpServletRequest request){
if (request.getHeader("x-forwarded-for") == null) {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return request.getHeader("x-forwarded-for");
}
}
/—————————————————————-/
辅助工具类 BeanUtil .java(手动注入)
public class BeanUtil implements ApplicationContextAware {
/** Spring上下文 */
private static ApplicationContext applicationContext;
/**
* 根据beanName获取对象
*
*/
public static Object getBean(String beanName) {
System.out.println("次数");
return applicationContext.getBean(beanName);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
return clazz.cast(getBean(beanName));
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
/——————————————————–/
辅助工具类SystemLog.java(方便日志信息传入)
传入信息为 PARAMETER:参数 METHOD:方法名 RUNTIME:运行时间
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {
String module() default "";
String methods() default "";
}
/——————————————————–/
po类
基本参数 id,用户,ip,访问url,调用方法,使用时间等
public class Log {
private Integer id;
private String loginaccount;
private String loginip;
private String actionurl;
private String module;
private String method;
private String actiontime;
private String description;
private String gmtcreate;
private String starttime;
private String endtime;
private int state;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLoginaccount() {
return loginaccount;
}
public void setLoginaccount(String loginaccount) {
this.loginaccount = loginaccount == null ? null : loginaccount.trim();
}
public String getLoginip() {
return loginip;
}
public void setLoginip(String loginip) {
this.loginip = loginip == null ? null : loginip.trim();
}
public String getActionurl() {
return actionurl;
}
public void setActionurl(String actionurl) {
this.actionurl = actionurl == null ? null : actionurl.trim();
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module == null ? null : module.trim();
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method == null ? null : method.trim();
}
public String getActiontime() {
return actiontime;
}
public void setActiontime(String actiontime) {
this.actiontime = actiontime == null ? null : actiontime.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public String getGmtcreate() {
return gmtcreate;
}
public void setGmtcreate(String gmtcreate) {
this.gmtcreate = gmtcreate == null ? null : gmtcreate.trim();
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime == null ? null : starttime.trim();
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime == null ? null : endtime.trim();
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public String toString() {
return "Log [id=" + id + ", loginaccount=" + loginaccount
+ ", loginip=" + loginip + ", actionurl=" + actionurl
+ ", module=" + module + ", method=" + method + ", actiontime="
+ actiontime + ", description=" + description + ", gmtcreate="
+ gmtcreate + ", starttime=" + starttime + ", endtime="
+ endtime + ", state=" + state + "]";
}
}
/——————————————————————-/
SpringMVC 配置 applicationContext.xml
手动注入
<bean id="beanUtil" class="com.hzyc.registerSystem.tools.BeanUtil"></bean>
<bean id="initServiceLog" class="com.hzyc.registerSystem.services.impl.InitServiceImp"> </bean>
<!-- 日志记录类注入该service -->
<bean id="logAop" class="com.hzyc.registerSystem.tools.LogAopAction" name="logAop">
<property name="initServiceImp" ref="initServiceLog"></property>
</bean>
/——————————————————————-/
SpringMVC 配置 springmvcConfig.xml
<aop:aspectj-autoproxy expose-proxy="true"></aop:aspectj-autoproxy>
切口点
aop设置切口暴露为true
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术
手动注入 name为logAop,与后面匹配
往切口传值
将数据插入数据库 在serviceImp接值,并实现插入数据库