In Linux, viewing and analyzing logs is a core operation for daily maintenance or testing. Below are common and advanced commands for viewing logs and their usage scenarios.
1. Common commands for viewing historical logs
1) Regularly search for log information containing specific keywords in designated log files.
1) Ignore case sensitivity, allowing for matches of both “ERROR“ and “error“ keywords.
grep -i "error" log_file
2) Find logs that contain a specific keyword such as null pointer with surrounding lines (e.g., 1 0 0) in the logs.
grep -C 10 "null pointer" log_file
3) Find logs that contain keywords such as null pointer with preceding lines (e.g., 1 0 0) and following lines (e.g., 3 0 0) in the logs.
grep -B 10 -A 30 "null pointer" log_file
4) Reverse match to exclude specific keywords.
grep -v "info" log_file
5) If the log file is large, use pagination to view the logs. It is recommended to use less, which supports scrolling up and down, and searching.
grep "error" log_file | less
6) View the entire log file, scrolling down page by page.
cat log_file | more
7) View errors within a specific time range.
grep "2023-11-01" log_file | grep -i "error" | less
8) Display line numbers in the log file.
nl log_file
2. Find logs corresponding to keywords in log files.
1) Search for multiple log files containing keywords.
grep -l "failed log" /export/log/x*.log
2) Recursively search for files in a directory containing keywords.
grep -r "timeout" /export/log/
3) Advanced log viewing
1) sed: Extract logs based on line rules, accurately capturing segments.
sed -n '5000,10000p' log_file
2) awk: Analyze logs by column format, filtering and counting.
awk '$9==500' log_file
Note: The following log
192.168.1.1 – – [10/Oct/2023:10:00:00 +0800] “GET /index.html HTTP/1.1” 200 1024
$1: 192.168.1.1 ip
$2: –
$4: [10/Oct/2023:10:00:00 +0800]
$6: 200 (status code)
2. View real-time logs
1) Real-time tracking of the latest logs, including keywords.
tail -f log_file | grep -i "error"
2) Periodically refresh to check for updates using watch, suitable for low-frequency monitoring.
watch -n 2 'tail -n 10 log_file'
3) Multi-tail to monitor multiple log files in real-time, suitable for comparing logs.
sudo apt install multi-tail
multi-tail detail.log error.log# Real-time tracking of detailed logs and error logs.