Finding a string in docker logs of container

前端 未结 8 1056
南方客
南方客 2021-01-30 01:21

What is the best way to find a specific string in the logs of a docker container? Let\'s say I want to see all requests, that are made in the \"nginx\" docker image that came fr

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 02:02

    Additionally, I found it usefull to highlight some terms that I'm searching for in the logs. Especially on productive installations where a lot of log output is generated. In my case I want to highlight COUNT(*) statements. But with a simple grep I can't see the entire SQL statement since it's a multi line statement. This is possible with -E switch and some regex:

    For example, the following snippet search for all queries that contain COUNT(*) as well as count(*):

    docker logs  -f | grep --line-buffered -i -E --color "select count\(\*\)|$"
    

    Some explanation:

    • docker logs -f tell docker to follow the logs, so the filter applys also to new entrys like when viewing it using tail -f
    • greps --line-buffered switch flushes the output on every line, which is required to grep in real time when docker logs -f is used
    • -E is an extended regex pattern, required to apply our pattern that allow us returning also the non matching results
    • --color highlights the matched parts (seems the default behaviour on my Ubuntu 16.04 LTS, but maybe not on other distributions, so I included it here to be safe)
    • * is escaped to disable its special glob functionality, where (, and ) are masked to avoid their regex meaning as group, which is enabled by -E switch

    If the container logs to stderr, you can pipe them as Edoardo already wrote for a simple grep:

    docker logs  -f 2>&1 | grep --line-buffered -i -E --color "select count\(\*\)|$"
    

    The -f switch could be omitted if no live grep is wanted. In both cases, you see the entire log buth with highlighted search term like this:

提交回复
热议问题