Spring Boot教程(八)使用log4j實現http請求日誌入mongodb

準備工做

能夠先拿Chapter4-2-4工程爲基礎,進行後續的實驗改造。該工程實現了一個簡單的REST接口,一個對web層的切面,並在web層切面先後記錄http請求的日誌內容。html

經過自定義appender實現

思路:log4j提供的輸出器實現自Appender接口,要自定義appender輸出到MongoDB,只須要繼承AppenderSkeleton類,並實現幾個方法便可完成。java

引入mongodb的驅動

在pom.xml中引入下面依賴git

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.2.2</version>
</dependency>

實現MongoAppender

編寫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

    • connectionUrl:鏈接mongodb的串
    • databaseName:數據庫名
    • collectionName:集合名
  • 定義MongoDB的鏈接和操做對象,根據log4j.properties配置的參數初始化:spring

    • mongoClient:mongodb的鏈接客戶端
    • mongoDatabase:記錄日誌的數據庫
    • logsCollection:記錄日誌的集合
  • 重寫append函數:mongodb

    • 根據log4j.properties中的配置建立mongodb鏈接
    • LoggingEvent提供getMessage()函數來獲取日誌消息
    • 往配置的記錄日誌的collection中插入日誌消息
  • 重寫close函數:關閉mongodb的數據庫

配置log4j.properties

設置名爲mongodb的logger:app

  • 記錄INFO級別日誌
  • appender實現爲com.didispace.log.MongoAppende
  • mongodb鏈接地址:mongodb://localhost:27017
  • mongodb數據庫名:logs
  • mongodb集合名:logs_request
    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

    切面中使用mongodb logger

    修改後的代碼以下,主要作了如下幾點修改:ide

  • logger取名爲mongodb的
  • 經過getBasicDBObject函數從HttpServletRequest和JoinPoint對象中獲取請求信息,並組裝成BasicDBObject
    • getHeadersInfo函數從HttpServletRequest中獲取header信息
  • 經過logger.info(),輸出BasicDBObject對象的信息到mongodb
    @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實現更爲方便快捷。

相關文章
相關標籤/搜索