設置名爲mongodb的logger:html
log4j.logger.mongodb=INFO, mongodb # mongodb輸出 log4j.appender.mongodb=com.didispace.log.MongoAppender log4j.appender.mongodb.connectionUrl=mongodb://localhost:27017 log4j.appender.mongodb.databaseName=logs log4j.appender.mongodb.collectionName=logs_request
修改後的代碼以下,主要作了如下幾點修改:java
@Aspect @Order(1) @Component public class WebLogAspect { private Logger logger = Logger.getLogger("mongodb"); @Pointcut("execution(public * com.didispace.web..*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 獲取HttpServletRequest ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 獲取要記錄的日誌內容 BasicDBObject logInfo = getBasicDBObject(request, joinPoint); logger.info(logInfo); } private BasicDBObject getBasicDBObject(HttpServletRequest request, JoinPoint joinPoint) { // 基本信息 BasicDBObject r = new BasicDBObject(); r.append("requestURL", request.getRequestURL().toString()); r.append("requestURI", request.getRequestURI()); r.append("queryString", request.getQueryString()); r.append("remoteAddr", request.getRemoteAddr()); r.append("remoteHost", request.getRemoteHost()); r.append("remotePort", request.getRemotePort()); r.append("localAddr", request.getLocalAddr()); r.append("localName", request.getLocalName()); r.append("method", request.getMethod()); r.append("headers", getHeadersInfo(request)); r.append("parameters", request.getParameterMap()); r.append("classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); r.append("args", Arrays.toString(joinPoint.getArgs())); return r; } private Map<String, String> getHeadersInfo(HttpServletRequest request) { Map<String, String> map = new HashMap<>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
上述內容主要提供一個思路去實現自定義日誌的輸出和管理。咱們能夠經過jdbc實現日誌記錄到mongodb,也能夠經過spring-data-mongo來記錄到mongodb,固然咱們也能夠輸出到其餘數據庫,或者輸出到消息隊列等待其餘後續處理等。git
對於日誌記錄到mongodb,也能夠直接使用log4mongo實現更爲方便快捷。github
源碼來源web