Junior
How can you view an error and its context (10 lines before and after the error)?
sobes.tech AI
Answer from AI
You can use a combination of commands like grep, cat, and awk, or more advanced logging tools.
Using grep and cat:
# Find the line with the error and display it with line numbers
grep -n "Error" your_log_file.log
After finding the line number with the error, you can use cat and awk to display context:
# Suppose the error is on line 100
# Display lines 90 to 110
cat your_log_file.log | awk 'NR>=90 && NR<=110'
A more flexible approach with grep and -B (before) and -A (after) options:
# Display the line with the error and 10 lines before and after
grep -B 10 -A 10 "Error" your_log_file.log
Using less or more with search:
# Open the file in less
less your_log_file.log
# Inside less, perform search:
# /Error +10 # Jump to the line with the error and display the next page
# ?Error -10 # Jump to the line with the error and display the previous page
Centralized logging systems like ELK Stack (Elasticsearch, Logstash, Kibana), Splunk, or Loki provide convenient interfaces for searching logs and viewing context. In Kibana, for example, you can simply click on an error message and view surrounding entries.