2015-01-11 117 views
0

我正在尋找解析Varnish日誌文件的解決方案。它看起來像:用正則表達式解析日誌

178.232.38.87 - - [23/May/2012:14:01:05 +0200] "GET http://static.vg.no/iphone/js/front-min.js?20120509-1 HTTP/1.1" 200 2013 "http://touch.vg.no/" "Mozilla/5.0 (Linux; U; Android 2.3.3; en-no; HTC Nexus One Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1" 

有可以區分以下元素:

%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i"

,但我仍然不知道如何做到這一點。簡單的String.split(" ");將無法​​正常工作。

我知道正則表達式有一般規則,但最合適的是java。

感謝

+0

[Java解析日誌文件]的可能的重複(http://stackoverflow.com/questions/20349184/java-parse-log-file) – Jens

回答

2

我會想出一個方法來建立從根據他們可能/預期值相匹配的各個字段塊正則表達式。

String rexa = "(\\d+(?:\\.\\d+){3})"; // an IP address 
    String rexs = "(\\S+)";    // a single token (no spaces) 
    String rexdt = "\\[([^\\]]+)\\]";  // something between [ and ] 
    String rexstr = "\"([^\"]*?)\"";  // a quoted string 
    String rexi = "(\\d+)";    // unsigned integer 

    String rex = String.join(" ", rexa, rexs, rexs, rexdt, rexstr, 
           rexi, rexi, rexstr, rexstr); 

    Pattern pat = Pattern.compile(rex); 
    Matcher mat = pat.matcher(h); 
    if(mat.matches()){ 
     for(int ig = 1; ig <= mat.groupCount(); ig++){ 
      System.out.println(mat.group(ig)); 
     } 
    } 

當然的,可以湊合着用到位REXA或熱西乙線的rexs。

+0

很酷,它完美的作品。這個問題與IPv4有關。 – Jacob