spring log 日志管理

阅读更多

 

 

 

import java.util.Map;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
/**
 * Logger
 */
public class Logger {
	
	@Resource
	private LogService logService ;
	public Object record(ProceedingJoinPoint pjp){
		Log log = new Log();
		try {
			ActionContext ac = ActionContext.getContext(); 
			if(ac != null){
				Map session = ac.getSession();
				if(session != null){
					User user = (User) session.get("user");
					if(user != null){
						log.setOperator("" + user.getId() + ":" + user.getEmail());
					}
				}
			} 
			String mname = pjp.getSignature().getName();
			log.setOperName(mname); 
			Object[] params = pjp.getArgs();
			log.setOperParams(StringUtil.arr2Str(params)); 
			Object ret = pjp.proceed(); 
			log.setOperResult("success"); 
			if(ret != null){
				log.setResultMsg(ret.toString());
			}
			return ret ;
		} catch (Throwable e) {
			log.setOperResult("failure");
			log.setResultMsg(e.getMessage());
		}
		finally{
			logService.saveEntity(log);
		}
		return null ;
	}
}

 

 

	
	
	
		
	
		
		
		
		
		
		
		
		
			
		
	

 

 

 



	
	
		
		
		
			
				
			
		
	
	
	
	
		
		
		
			0 19 10 3 * ?
		
	
	
	
	
		
			
				
			
		
	

 

public class CreateLogTablesTask extends QuartzJobBean {

	
	private LogService logService ; 
	public void setLogService(LogService logService) {
		this.logService = logService;
	}
 
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException { 
		String tableName = LogUtil.generateLogTableName(1 );
		logService.createLogTable(tableName);
		 
		tableName = LogUtil.generateLogTableName(2);
		logService.createLogTable(tableName);
		 
		tableName = LogUtil.generateLogTableName(3);
		logService.createLogTable(tableName);
	}
}

  

public void createLogTable(String tableName){
		String sql = "create table if not exists " +tableName + " like logs" ;
		this.executeSQL(sql);
	}

  

 

 

public class LogUtil {
	 
	public static String generateLogTableName(int offset){
		Calendar c = Calendar.getInstance();
		// 2013
		int year = c.get(Calendar.YEAR);
		// 0 -11
		int month = c.get(Calendar.MONTH) + 1 + offset;
		
		if(month > 12){
			year ++ ;
			month = month - 12 ;
		}
		if(month < 1){
			year -- ;
			month = month + 12 ;
		}
		DecimalFormat df = new DecimalFormat();
		df.applyPattern("00");
		return "logs_" + year + "_" + df.format(month) ;
	}
}

 

public void saveEntity(Log t) {
		//insert into logs_2013_9()
		String sql = "insert into " 
				+ LogUtil.generateLogTableName(0) 
				+ "(id,operator,opername,operparams,operresult,resultmsg,opertime) "
				+ "values(?,?,?,?,?,?,?)" ;
		UUIDHexGenerator uuid = new UUIDHexGenerator();
		String id = (String) uuid.generate(null, null);
		this.executeSQL(sql, id,
							t.getOperator(),
							t.getOperName(),
							t.getOperParams(),
							t.getOperResult(),
							t.getResultMsg(),
							t.getOperTime());
	}

  

   

  

 

 

 

 

 

 

 

 

你可能感兴趣的:(spring,log,日志管理)