How can I capture Java exceptions, including the stack trace, from a log file using grep?

后端 未结 2 1663
难免孤独
难免孤独 2021-02-14 07:52

Summary

I am trying to fetch logs from a log file using the grep command. However, I can match time stamps, but am not getting the full stack trace I need.

Lo

2条回答
  •  独厮守ぢ
    2021-02-14 08:31

    Use Context for Fixed-Length Traces

    In your original post, you show a single three-line entry. If you know that each exception message with a stack trace is exactly three lines long, then you can use one of the --after-context flags (if supported by your grep) to get all three lines. For example, to pull all exceptions along with the stack trace:

    $ fgrep -A2 'Exception message' SystemOut.log
    [1/10/16 23:55:33:018 PST] 00000057 ServerObj E   SECJ0373E: Exception message
    at com.own.ws.wim.util.UniqueNameHelper.formatUniqueName(UniqueNameHelper.java:102)
    at com.own.ws.wim.ProfileManager.getImpl(ProfileManager.java:1569)
    

    Use Multi-Line Expressions for Variable-Length Stack Traces

    However, if you don't know how many lines are in the stack trace, then you need a multiline regex with a stop-pattern. For this, you need a grep with the Perl-compatible regular expression (PCRE) library compiled in. For example, with grep -PM or pcregrep -M:

    $ pcregrep -M 'Exception message[^\[]+' SystemOut.log
    [1/10/16 23:55:33:018 PST] 00000057 ServerObj E   SECJ0373E: Exception message
    at com.own.ws.wim.util.UniqueNameHelper.formatUniqueName(UniqueNameHelper.java:102)
    at com.own.ws.wim.ProfileManager.getImpl(ProfileManager.java:1569)
    

    This will print each line with an exception, using the square bracket that starts a new timestamp as the stop-pattern. You can certainly adjust the regular expression to suit your needs, or pipe the results to another grep to filter specific timestamps in or out.

    This worked for me given the corpus you originally posted. Your mileage may vary.

提交回复
热议问题