Logging
Chapter 52: Logging and Log Management
Section titled “Chapter 52: Logging and Log Management”Overview
Section titled “Overview”Logging is critical for system administration, security auditing, troubleshooting, and compliance. Linux provides robust logging infrastructure including rsyslog, journald, and various log management tools. This chapter covers everything needed for effective log management.
52.1 Linux Logging Architecture
Section titled “52.1 Linux Logging Architecture”Logging Components
Section titled “Logging Components” Linux Logging Architecture+------------------------------------------------------------------+| || +------------------------+ || | Logging Components | || +------------------------+ || | || +---------------------+---------------------+ || | | | || v v v || +----------+ +----------+ +----------+ || |Applications| |rsyslog | |journald | || | | | | | | || | - Services| | - Local | | - systemd| || | - Daemons | | logs | | logs | || +----------+ +----------+ +----------+ || | | | || +---------------------+---------------------+ || | || +---------------------+---------------------+ || | | | || v v v || +----------+ +----------+ +----------+ || |/var/log/ | |/var/log/ | | Journal | || |messages | | syslog | |Database | || +----------+ +----------+ +----------+ || |+------------------------------------------------------------------+B --> JJ --> L2R --> L1### Key Log Files
```bash# System logs/var/log/messages # General system messages (Debian/Ubuntu)/var/log/syslog # General system messages (Arch/RHEL)/var/log/dmesg # Kernel ring buffer/var/log/kern.log # Kernel messages/var/log/boot.log # Boot messages
# Application logs/var/log/nginx/ access.log # HTTP access logs error.log # Error logs/var/log/apache2/ access.log error.log/var/log/postgresql/ postgresql.log/var/log/mysql/ error.log slow.log
# Security logs/var/log/auth.log # Authentication logs (Debian)/var/log/secure # Authentication logs (RHEL/Arch)/var/log/faillog # Failed login attempts/var/log/lastlog # Last login records
# Systemd journaljournalctl # Query systemd journal52.2 Systemd Journal (journald)
Section titled “52.2 Systemd Journal (journald)”Basic journalctl Usage
Section titled “Basic journalctl Usage”# View all logs (paginated)journalctl
# View kernel messagesjournalctl -kjournalctl --dmesg
# View logs for specific servicejournalctl -u nginx.servicejournalctl -u postgresql
# View logs since specific timejournalctl --since "2024-01-01"journalctl --since "1 hour ago"journalctl --since "yesterday"
# View logs in time rangejournalctl --since "2024-01-01" --until "2024-01-02"
# Follow logs in real-timejournalctl -fjournalctl -fu nginx.service
# View recent logsjournalctl -n 100journalctl -n 100 --no-pager
# Filter by priority# 0=emergency, 1=alert, 2=critical, 3=error, 4=warning, 5=notice, 6=info, 7=debugjournalctl -p errjournalctl -p warning..emergAdvanced Filtering
Section titled “Advanced Filtering”# By process IDjournalctl _PID=1234
# By user IDjournalctl _UID=1000
# By executablejournalctl /usr/bin/nginx
# By devicejournalctl _DEVICE=/dev/sda1
# By systemd unitjournalctl -u nginx.service -u php-fpm.service
# Combined filtersjournalctl -u nginx --since "1 hour ago" -p error
# Boot-specific logsjournalctl --list-bootsjournalctl -b -1 # Previous bootjournalctl -b 2 # Boot 2 agoJournal Configuration
Section titled “Journal Configuration”# View current configurationcat /etc/systemd/journald.conf
# Configuration options# /etc/systemd/journald.conf[Journal]SystemMaxUse=500M # Max disk usageRuntimeMaxUse=100M # Max in-memory storageMaxRetentionSec=1month # Max retention timeMaxFileSec=1week # Rotate weeklyStorage=persistent # persistent, volatile, auto, noneCompress=yes # Compress old entriesForwardToSyslog=yes # Forward to rsyslogJournal Storage Management
Section titled “Journal Storage Management”# Disk usagejournalctl --disk-usage
# Vacuum old logsjournalctl --vacuum-size=100M # Keep only 100MBjournalctl --vacuum-time=2weeks # Keep 2 weeksjournalctl --vacuum-files=5 # Keep 5 files
# Make journal persistentsudo mkdir -p /var/log/journalsudo systemd-tmpfiles --create --prefix /var/log/journalsudo systemctl restart systemd-journald52.3 rsyslog
Section titled “52.3 rsyslog”rsyslog Configuration
Section titled “rsyslog Configuration”# Main configuration file/etc/rsyslog.conf
# Modules$ModLoad imuxsock # Local message input$ModLoad imklog # Kernel messages$ModLoad imudp # UDP receiver$ModLoad imtcp # TCP receiver
# Rules format# facility.priority action
# Facilities: auth, authpriv, cron, daemon, kern, lpr, mail, news, syslog, user, uucp, local0-7# Priorities: debug, info, notice, warning, err, crit, alert, emergRule Examples
Section titled “Rule Examples”# Log everything to file*.* /var/log/all.log
# Log auth messagesauth.* /var/log/auth.logauthpriv.* /var/log/secure
# Log mailmail.* /var/log/maillogmail.err /var/log/mail.err
# Log croncron.* /var/log/cron
# Log kernelkern.* /var/log/kern.log
# Discard (don't log)mail.* ~
# Forward to remote server*.* @remote-host:514*.* @@remote-host:514 # TCP
# Log to console*.emerg /dev/consoleRemote Logging
Section titled “Remote Logging”# Server configuration (/etc/rsyslog.conf)# Enable UDP/TCP receptionmodule(load="imudp")input(type="imudp" port="514")
module(load="imtcp")input(type="imtcp" port="514")
# Client configuration*.* @rsyslog-server.example.com:514
# TLS encrypted logging$DefaultNetstreamDriver gtls$ActionSendStreamDriverMode 1$ActionSendStreamDriverAuthMode x509/name$ActionSendStreamDriverPermittedNode rsyslog-client*.* @@(o)gsecs.tls.example.com:651452.4 Log Rotation
Section titled “52.4 Log Rotation”logrotate Configuration
Section titled “logrotate Configuration”# Main configuration/etc/logrotate.conf
# Include directory for service-specific configsinclude /etc/logrotate.d/
# Example logrotate.confdaily # Rotate dailyrotate 14 # Keep 14 dayscompress # Compress old logsdelaycompress # Don't compress immediatelymissingok # OK if file missingnotifempty # Don't rotate if emptycreate 0640 root adm # Permissions for new logsdateext # Date-based rotationdateformat -%Y%m%d # Date format
# Additional optionsmaxsize 100M # Rotate if > 100MBminsize 10M # Don't rotate if < 10MBsize 100M # Size-based rotationsharedscripts # Run postrotate once per rotationprerotate/endscript # Pre-rotation commandspostrotate/endscript # Post-rotation commandsService-Specific Configuration
Section titled “Service-Specific Configuration”/var/log/nginx/*.log { daily missingok rotate 52 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid` endscript}
# /etc/logrotate.d/apache2/var/log/apache2/*.log { daily missingok rotate 14 compress delaycompress notifempty create 640 root adm sharedscripts postrotate if [ -f /var/run/apache2/apache2.pid ]; then /usr/sbin/invoke-rc.d apache2 graceful > /dev/null fi endscript}
# /etc/logrotate.d/syslog/var/log/cron.log/var/log/maillog/var/log/messages/var/log/syslog { daily rotate 7 missingok notifempty compress sharedscripts postrotate /usr/lib/rsyslog/rsyslog-rotate endscript}Manual Log Rotation
Section titled “Manual Log Rotation”# Force rotationlogrotate -f /etc/logrotate.conflogrotate -d -f /etc/logrotate.d/nginx # Debug mode
# Rotate all logs nowlogrotate -f /etc/logrotate.conf52.5 Analyzing Logs
Section titled “52.5 Analyzing Logs”Common Log Analysis Tasks
Section titled “Common Log Analysis Tasks”# Count lines in logwc -l /var/log/messages
# Find errorsgrep -i error /var/log/messagesgrep -E "error|fail|critical" /var/log/messages
# Find specific time windowsed -n '/Jan 15 10:00/,/Jan 15 11:00/p' /var/log/messages
# Failed SSH attemptsgrep "Failed password" /var/log/auth.loggrep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn
# Most common errorsgrep error /var/log/messages | awk '{print $5}' | sort | uniq -c | sort -rn
# Disk space issuesgrep -i "no space" /var/log/messages
# Service restartsgrep -i "started\|stopped\|restarted" /var/log/messages | tail -20Log Analysis Commands
Section titled “Log Analysis Commands”# tail -f for live monitoringtail -f /var/log/messagestail -f /var/log/nginx/error.log
# Watch commandwatch -n 1 'tail -20 /var/log/messages'
# awk examplesawk '/error/ {print $1,$2,$5}' /var/log/messagesawk '/ssh/ {print $1,$2,$3,$11}' /var/log/auth.log
# sed for extractionsed -n '/Failed password/,/192.168/p' /var/log/auth.log
# cut for column extractioncut -d' ' -f1-4 /var/log/messages | headLogwatch
Section titled “Logwatch”# Install logwatchsudo pacman -S logwatch
# Configuration/etc/logwatch/conf/logwatch.conf
# Run manually/usr/sbin/logwatch --output stdout --detail high --service all
# Email report/usr/sbin/logwatch --output mail --mailto admin@example.com --detail high52.6 Centralized Logging
Section titled “52.6 Centralized Logging”ELK Stack Overview
Section titled “ELK Stack Overview” ELK Stack Architecture+------------------------------------------------------------------+| || Clients Logstash Elasticsearch Grafana || +--------+ +--------+ +-----------+ +------+ || |Server 1|───────────>| | | | | | || +--------+ | | | | | | || +--------+ rsyslog | Logstash|------>|Elasticsearch|--> |Grafana| || |Server 2|───────────>| | | | | | || +--------+ | | | | | | || +--------+ +--------+ +-----------+ +------+ || |Server N| || +--------+ || |+------------------------------------------------------------------+Setting Up Filebeat
Section titled “Setting Up Filebeat”# Install filebeatsudo pacman -S filebeat
# Configuration# /etc/filebeat/filebeat.ymlfilebeat.inputs: - type: log enabled: true paths: - /var/log/*.log - /var/log/nginx/*.log fields: service: syslog fields_under_root: true
output.logstash: hosts: ["logstash.example.com:5044"]
# Enable filebeat modulesfilebeat modules enable systemfilebeat modules enable nginx
# Start servicesudo systemctl enable --now filebeatLoki (Prometheus Stack)
Section titled “Loki (Prometheus Stack)”# Docker-compose for Loki# docker-compose.ymlversion: '3'services: loki: image: grafana/loki:2.9.0 ports: - "3100:3100" volumes: - ./config:/etc/loki - ./data:/loki
promtail: image: grafana/promtail:2.9.0 volumes: - /var/log:/var/log - ./config:/etc/promtail command: -config.file=/etc/promtail/config.yml
grafana: image: grafana/grafana:latest ports: - "3000:3000"52.7 Log Security
Section titled “52.7 Log Security”Protecting Log Files
Section titled “Protecting Log Files”# Set proper permissionschmod 640 /var/log/messageschmod 640 /var/log/securechown root:adm /var/log/messages
# Immutable logs (append only)chattr +a /var/log/messages# To remove: chattr -a /var/log/messages
# Audit logging for log accessauditctl -w /var/log/messages -p wa -k log_modifications
# Monitor log changesinotifywait -m /var/log/ -e modify -e create -e deleteCompliance Considerations
Section titled “Compliance Considerations”# Ensure logs are not tampered with# Use write-once media for critical logs# Implement log signing for integrity# Regular backup of logs
# PCI-DSS requirements# - Log retention for 1 year# - 3 months easily accessible# - File integrity monitoring# - Time synchronization52.8 Troubleshooting Examples
Section titled “52.8 Troubleshooting Examples”High Disk Space from Logs
Section titled “High Disk Space from Logs”# Find largest log filesdu -sh /var/log/*du -sh /var/log/* | sort -rh | head -10
# Find largest directoriesdu -shx /var/log/* 2>/dev/null | sort -rh | head -10
# Check for log explosionls -lahS /var/log | head -10Service Not Logging
Section titled “Service Not Logging”# Check if service logs to journaljournalctl -u service-name -n 50
# Check rsyslog runningsystemctl status rsyslog
# Check journald runningsystemctl status systemd-journald
# Check log directory permissionsls -la /var/log/service/
# Restart logging servicessudo systemctl restart rsyslogsudo systemctl restart systemd-journaldApplication Not Logging
Section titled “Application Not Logging”# Check application configuration# Ensure logging level is not set to 'quiet'# Check log file path exists
# For systemd services# Add StandardOutput=file:/var/log/app.log# Add StandardError=file:/var/log/app-error.log52.9 Practical Scripts
Section titled “52.9 Practical Scripts”Log Analysis Script
Section titled “Log Analysis Script”#!/bin/bashLOGFILE=${1:-/var/log/messages}REPORT="/tmp/log_report_$(date +%Y%m%d).txt"
echo "=== Log Analysis Report ===" > "$REPORT"echo "Generated: $(date)" >> "$REPORT"echo "" >> "$REPORT"
# Error countecho "=== Error Summary ===" >> "$REPORT"grep -ci error "$LOGFILE" >> "$REPORT" 2>/dev/null || echo "0" >> "$REPORT"
# Top 10 errorsecho "" >> "$REPORT"echo "=== Top 10 Errors ===" >> "$REPORT"grep -i error "$LOGFILE" 2>/dev/null | awk '{print $5}' | sort | uniq -c | sort -rn | head -10 >> "$REPORT"
# Failed loginsecho "" >> "$REPORT"echo "=== Failed Login Attempts ===" >> "$REPORT"grep "Failed password" "$LOGFILE" 2>/dev/null | tail -20 >> "$REPORT"
# Disk space warningsecho "" >> "$REPORT"echo "=== Disk Space Warnings ===" >> "$REPORT"grep -i "no space\|disk full\|quota" "$LOGFILE" 2>/dev/null | tail -10 >> "$REPORT"
# Service restartsecho "" >> "$REPORT"echo "=== Service Restarts ===" >> "$REPORT"grep -i "started\|stopped" "$LOGFILE" 2>/dev/null | tail -20 >> "$REPORT"
cat "$REPORT"Summary
Section titled “Summary”In this chapter, you learned:
- ✅ Linux logging architecture (rsyslog, journald)
- ✅ Using journalctl for systemd logs
- ✅ rsyslog configuration and rules
- ✅ Log rotation with logrotate
- ✅ Log analysis techniques
- ✅ Centralized logging with ELK/Loki
- ✅ Log security and compliance
- ✅ Troubleshooting log issues
Next Chapter
Section titled “Next Chapter”Chapter 10: Monitoring and Alerting
Last Updated: February 2026