正则表达式以匹配整个Java异常Stacktrace

时间:2018-07-12 13:21:15

标签: java regex logging grep

给出Java应用程序的标准日志文件:

<template>
  <div>
    <button v-on:click="getInfo(service)">GET INFO</button> 
    <p v-bind:id="'info'+service.id"/>
  </div>  
</template>

什么是匹配任何Java INFO [main] (AutoMain.java:133) - querying data 1 DEBUG [main] (AutoMain.java:142) - data 1 count: 23180 INFO [main] (AutoMain.java:151) - querying data 2 ERROR [main] (AutoMain.java:607) - Failure in auto java.net.ConnectException: Connection refused (Connection refused) at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at java.net.Socket.<init>(Socket.java:434) at java.net.Socket.<init>(Socket.java:211) at com.myCompany.client.ClientIOFactory$1.<init>(ClientIOFactory.java:17) at com.myCompany.client.ClientIOFactory.lambda$clientIOFactoryFromSocket$0(ClientIOFactory.java:15) at com.myCompany.client.queryData(Client.java:83) at com.myCompany.client.queryData(Client.java:91) at com.myCompany.queryOptData(InstantAutomaton.java:153) at com.myCompany.AutoMain.main(InstantAutomaton.java:426) 的整个堆栈跟踪的正则表达式?

很容易匹配包含“异常”的任何一行:

Exception

但是我也希望所有后续的“ at”语句。因此,结果匹配的字符串应为:

grep "Exception" log.txt

预先感谢您的考虑和答复。

2 个答案:

答案 0 :(得分:3)

使用Java +8,您可以做到:

(?m)^.*?Exception.*(?:\R+^\s*at .*)+

请参见live demo here

但是在grep中,由于默认情况下它一次处理一行,因此您可以将Exception或以at开头的行进行匹配:

grep -P '(?m)^(?:\S+?Exception|\h+at )' file

答案 1 :(得分:1)

当您可以在任何UNIX机器上的任何shell中使用任何awk来进行此操作时,请不要使用复杂的,不可移植的正则表达式:

$ awk '/^[^ ]/{f=0} /Exception/{f=1} f' file
java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at com.myCompany.client.ClientIOFactory$1.<init>(ClientIOFactory.java:17)
    at com.myCompany.client.ClientIOFactory.lambda$clientIOFactoryFromSocket$0(ClientIOFactory.java:15)
    at com.myCompany.client.queryData(Client.java:83)
    at com.myCompany.client.queryData(Client.java:91)
    at com.myCompany.queryOptData(InstantAutomaton.java:153)
    at com.myCompany.AutoMain.main(InstantAutomaton.java:426)