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

后端 未结 2 1676
难免孤独
难免孤独 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:34

    (From my answer here: https://stackoverflow.com/a/16064081/430128)

    Here is a quick-and-dirty grep expression... if you are using a logger such as log4j than the first line of the exception will generally contain WARN or ERROR, the next line will contain the Exception name, and optionally a message, and then the subsequent stack trace will begin with one of the following:

    1. "\tat" (tab + at)
    2. "Caused by: "
    3. "\t... more" (these are the lines that indicate the number of frames in the stack not shown in a "Caused by" exception)
    4. An Exception name (and perhaps message) before the stack

    We want to get all of the above lines, so the grep expression is:

    grep -P "(WARN|ERROR|^\tat |Exception|^Caused by: |\t... \d+ more)"

    It assumes an Exception class always contains the word Exception which may or may not be true, but this is quick-and-dirty after all.

    Adjust as necessary for your specific case.

提交回复
热议问题