能夠先拿Chapter4-2-4工程爲基礎,進行後續的實驗改造。該工程實現了一個簡單的REST接口,一個對web層的切面,並在web層切面先後記錄http請求的日誌內容。html
思路:log4j提供的輸出器實現自Appender接口,要自定義appender輸出到MongoDB,只須要繼承AppenderSkeleton類,並實現幾個方法便可完成。java
在pom.xml中引入下面依賴git
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.2.2</version> </dependency>
編寫MongoAppender類繼承AppenderSkeleton,實現以下:github
public class MongoAppender extends AppenderSkeleton { private MongoClient mongoClient; private MongoDatabase mongoDatabase; private MongoCollection<BasicDBObject> logsCollection; private String connectionUrl; private String databaseName; private String collectionName; @Override protected void append(LoggingEvent loggingEvent) { if(mongoDatabase == null) { MongoClientURI connectionString = new MongoClientURI(connectionUrl); mongoClient = new MongoClient(connectionString); mongoDatabase = mongoClient.getDatabase(databaseName); logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class); } logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage()); } @Override public void close() { if(mongoClient != null) { mongoClient.close(); } } @Override public boolean requiresLayout() { return false; } // 省略getter和setter }
定義MongoDB的配置參數,可經過log4j.properties配置:web
定義MongoDB的鏈接和操做對象,根據log4j.properties配置的參數初始化:spring
重寫append函數:mongodb
重寫close函數:關閉mongodb的數據庫
設置名爲mongodb的logger:app
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
修改後的代碼以下,主要作了如下幾點修改:ide
@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,固然咱們也能夠輸出到其餘數據庫,或者輸出到消息隊列等待其餘後續處理等。
對於日誌記錄到mongodb,也能夠直接使用log4mongo實現更爲方便快捷。