Using tail to follow log files

Log files are created for a reason. They come in handy when you’re debugging an unexpected HTTP response for example. But keep refreshing a log file is not an efficient way of working. To automatically see additions to a file you can use the tail command in follow mode.

Using tail in follow mode

The tail command is used to print the last lines in a file. By default it will show only the last 10 lines.

$ tail /var/log/nginx/access.log
::1 - - [27/Feb/2020:19:17:08 +0100] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
...
$

The example above showed that the command finished after printing the last 10 lines. To keep the command running we need to use the -f option to follow additions added to the file.

When you pass the -f option you will see that the command keeps running and that lines get added when you make another request to NGINX.

$ tail -f /var/log/nginx/access.log
::1 - - [27/Feb/2020:19:19:28 +0100] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
...

Tail multiple files

When necessary you can tail multiple files at the same time. To do this you add a second file path as an argument. This will show the file name as a header above new entries.

$ tail -f /var/log/nginx/access.log /var/log/nginx/error.log
...
==> /var/log/nginx/access.log <==
::1 - - [27/Feb/2020:19:24:38 +0100] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
...

Filter tail results with grep

If you know what you’re looking for you can combine tail with grep. To search for a specific HTTP status for example. This way you’ll only see lines containing the string “404”.

$ sudo tail -f /var/log/nginx/access.log | grep "404"
::1 - - [27/Feb/2020:13:13:24 +0100] "GET /favicon.ico HTTP/1.1" 404 548 "http://example.me/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"

See Also

6 Non-Programming Books for Programmers