Skip to content

Querying Logs

The journalctl utility is the primary tool for querying and analyzing logs managed by the systemd journal. It allows administrators to filter, search, and inspect logs from services, kernel events, and user sessions. This section covers techniques for querying and filtering logs effectively.


Basic Querying with journalctl

To retrieve logs, use journalctl with time-based filters or to follow real-time logs.
Example:

# Show logs from the last hour
journalctl --since "1 hour ago"

# Follow real-time logs (similar to 'tail -f')
journalctl -f

Use --until to limit logs to a specific time range:

journalctl --since "2023-10-01 08:00:00" --until "2023-10-01 09:00:00"


Filtering by Unit, Service, or Process

Filter logs for a specific systemd unit (e.g., a service or target):

journalctl -u sshd.service

Filter by log level (e.g., error, warning):

journalctl --level=err

Combine filters for precise results:

# Show error logs for the apache2 service
journalctl -u apache2.service --level=err


Advanced Filtering with journalctl Options

Use --grep to search for specific text in logs:

journalctl --grep="Failed to bind"

For more complex patterns, use --grep with regular expressions:

journalctl --grep="^Failed" --color

Filter by process ID (PID) or unit name using _PID or _SYSTEMD_UNIT:

journalctl _PID=1234
journalctl _SYSTEMD_UNIT=nginx.service


Analyzing and Exporting Logs

Export logs to a file for analysis:

journalctl -u sshd.service > sshd_logs.txt

Use --output=json to extract structured data:

journalctl --output=json

For advanced analysis, pipe logs to tools like jq for JSON processing:

journalctl --output=json-pretty | jq '.'


Key takeaways

  • Use --since and --until to narrow logs to specific time ranges.
  • Filter by unit, service, or log level to focus on relevant entries.
  • Combine --grep and regular expressions for precise text matching.
  • Export logs to files or use JSON output for structured analysis.
  • Leverage --rotate and log rotation settings to manage storage efficiently.