在SpringMVC中打印完整的AccessLog

轉(zhuǎn)載請注明來源 賴賴的博客

導(dǎo)語

總要造一下輪子才知道別人的輪子有多厲害

最近筆者遇到一個問題:在SpringMVC框架下蜒秤,沒有直接的方式可以打印完整的AccessLog,因為request body 和response body是通過inputstream和outputstream來封裝的菩佑,在使用過很多人提供的方式后瘾婿,發(fā)現(xiàn)效果總是不盡人意徙菠,所以自己摸索了一下消返,完成了這個功能

請慎重在生產(chǎn)環(huán)境使用這個功能,因為打印完整的AccessLog是一個很大的消耗

項目工程目錄結(jié)構(gòu)和代碼獲取地址

https://github.com/laiyijie/spring-access-log-filter

詳解核心類AccessLogFilter

完整代碼如下:

public class AccessLogFilter extends OncePerRequestFilter {
    private static final Logger logger = LogManager.getLogger(AccessLogFilter.class);

    private String usernameKey = "username";
    private Integer payloadMaxLength = 1024;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        Long startTime = System.currentTimeMillis();
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

        filterChain.doFilter(requestWrapper, responseWrapper);

        String requestPayload = getPayLoad(requestWrapper.getContentAsByteArray(),
                request.getCharacterEncoding());
        String responsePayload = getPayLoad(responseWrapper.getContentAsByteArray(),
                response.getCharacterEncoding());
        responseWrapper.copyBodyToResponse();
        BLog.accessJsonLogBuilder()
            .addRequestPayLoad(requestPayload)
            .addResponsePayLoad(responsePayload)
            .put(request, usernameKey)
            .put(response)
            .put("_COST_", System.currentTimeMillis() - startTime)
            .log();
    }

    private String getPayLoad(byte[] buf, String characterEncoding) {
        String payload = "";
        if (buf == null) return payload;
        if (buf.length > 0) {
            int length = Math.min(buf.length, getPayloadMaxLength());
            try {
                payload = new String(buf, 0, length, characterEncoding);
            } catch (UnsupportedEncodingException ex) {
                payload = "[unknown]";
            }
        }
        return payload;
    }


    public String getUsernameKey() {
        return usernameKey;
    }

    public void setUsernameKey(String usernameKey) {
        this.usernameKey = usernameKey;
    }

    public Integer getPayloadMaxLength() {
        return payloadMaxLength;
    }

    public void setPayloadMaxLength(Integer payloadMaxLength) {
        this.payloadMaxLength = payloadMaxLength;
    }
}

其核心思想是實現(xiàn)了OncePerRequestFilter這個虛基類劣领,而這個虛基類是實現(xiàn)了Filter接口姐军,并且要基于SpringMVC框架的,因此這個方法只能適用于SpringMVC工程

核心方法是doFilterInternal

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {

    Long startTime = System.currentTimeMillis();
    ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
    ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

    filterChain.doFilter(requestWrapper, responseWrapper);

    String requestPayload = getPayLoad(requestWrapper.getContentAsByteArray(),
            request.getCharacterEncoding());
    String responsePayload = getPayLoad(responseWrapper.getContentAsByteArray(),
            response.getCharacterEncoding());
    responseWrapper.copyBodyToResponse();
    BLog.accessJsonLogBuilder()
        .addRequestPayLoad(requestPayload)
        .addResponsePayLoad(responsePayload)
        .put(request, usernameKey)
        .put(response)
        .put("_COST_", System.currentTimeMillis() - startTime)
        .log();
}

首先通過

ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

這兩個方式對請求和返回進(jìn)行包裝(讓body可以被緩存),這樣來解決inputstream不能多次讀取的問題

調(diào)用

filterChain.doFilter(requestWrapper, responseWrapper);

來執(zhí)行其他的filter之后

可以通過

    String requestPayload = getPayLoad(requestWrapper.getContentAsByteArray(),
            request.getCharacterEncoding());
    String responsePayload = getPayLoad(responseWrapper.getContentAsByteArray(),
            response.getCharacterEncoding());

這種方式取出request和response的payload奕锌,不要忘記

    responseWrapper.copyBodyToResponse();

重新寫入response

最后打印出整個log

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末著觉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子惊暴,更是在濱河造成了極大的恐慌饼丘,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辽话,死亡現(xiàn)場離奇詭異肄鸽,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)油啤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進(jìn)店門典徘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人益咬,你說我怎么就攤上這事逮诲。” “怎么了幽告?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵汛骂,是天一觀的道長。 經(jīng)常有香客問我评腺,道長帘瞭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任蒿讥,我火速辦了婚禮蝶念,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘芋绸。我一直安慰自己媒殉,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布摔敛。 她就那樣靜靜地躺著廷蓉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪马昙。 梳的紋絲不亂的頭發(fā)上桃犬,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天,我揣著相機(jī)與錄音行楞,去河邊找鬼攒暇。 笑死,一個胖子當(dāng)著我的面吹牛子房,可吹牛的內(nèi)容都是我干的形用。 我是一名探鬼主播就轧,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼田度!你這毒婦竟也來了妒御?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤镇饺,失蹤者是張志新(化名)和其女友劉穎乎莉,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體兰怠,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年李茫,在試婚紗的時候發(fā)現(xiàn)自己被綠了揭保。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡魄宏,死狀恐怖秸侣,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情宠互,我是刑警寧澤味榛,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站予跌,受9級特大地震影響搏色,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜券册,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一频轿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧烁焙,春花似錦航邢、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至九火,卻和暖如春赚窃,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岔激。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工考榨, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鹦倚。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓河质,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子掀鹅,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容