2

We all know that we can search for a string in a log file and show the surroundings lines to the searched string:
grep -AXX -BXX "searched" file.log

Is possible do the same with the docker logs command?
I want to do is that if already know the string i'm searching happened around one hour ago, using "since" with "after" and "before", get only the result and not all the log, for example something like this:
docker logs --since=65m -A20 -B5 "searched string" [ID]

By now i copy all to a file, resulting sometimes a big file, and use a grep:
docker logs --since=65m [ID] >> file.log
grep -AXX -BXX "searched" file.log

Juanjo
  • 41
  • 1
  • 7
  • You can just pipe the output from `docker logs` to `grep`: `docker logs --since=65m -A20 -B5 | grep "search string"` – larsks Jan 25 '21 at 13:40

2 Answers2

5

According to documentation you cannot. However, you can grep with pipe

docker logs | grep "whatever"

stackoverflow answer for grep

docker documentation about logs

Alternative for Development

However for development purposes I am using datalust/seq - just add the image to your docker-compose file and with small configuration (depends on language which you are using) redirect logs to nice searchable portal.

# docker compose 
 seq:
    image: datalust/seq:latest 
    environment:
      - ACCEPT_EULA=Y
    ports:
      - "8082:80"

The portal (under http://localhost:8082 as I redirected default 80 port from Container to my 8082 port): seq image

Alternative for Production

For production purposes I would recommend to use something which is able to automatically collect logs from stdout and stderr like:

To provide the highest standards to your app regarding logging and monitoring.

Michał Jarzyna
  • 1,836
  • 18
  • 26
3

grep will read from stdin when you don't give it a file. Specifically with docker logs, you'll want to merge stdout and stderr together using the 2>&1 notation. The result looks like:

 docker logs --since=65m [ID] 2>&1 | grep -A20 -B5 "searched string"
BMitch
  • 231,797
  • 42
  • 475
  • 450
  • For a discussion on what's going on with this redirection, see [What does 2>&1 mean](https://stackoverflow.com/questions/818255/what-does-21-mean) – Tracy Logan Sep 22 '22 at 23:32