Skip to content

Log Management ​

Why Logs Are Needed ​

When something breaks, logs let you trace when the problem happened and what state the system was in. Without logs, the issue is hard to reproduce and the root cause is impossible to analyze.

Writing Logs: The Basics ​

bash
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
LOG_FILE=/var/log/agent-app/monitor.log

echo "[$TIMESTAMP] PID:$PID CPU:${CPU}% MEM:${MEM}% DISK_USED:${DISK}%" >> $LOG_FILE

>> appends to the existing file. > overwrites the existing content.

Managing Log Size (logrotate) ​

If you leave logs alone, they fill up the disk. logrotate manages them automatically.

bash
# Create a config file
vi /etc/logrotate.d/agent-app

# Contents
/var/log/agent-app/monitor.log {
    size 10M        # rotate when over 10MB
    rotate 10       # keep at most 10 files
    compress        # gzip the older files
    missingok       # continue without error if the file is missing
    notifempty      # do not rotate if the file is empty
}

Implementing It Directly in the Script ​

bash
LOG_FILE=/var/log/agent-app/monitor.log
MAX_SIZE=$((10 * 1024 * 1024))  # 10MB

if [ -f "$LOG_FILE" ] && [ $(stat -c%s "$LOG_FILE") -ge $MAX_SIZE ]; then
    mv "$LOG_FILE" "${LOG_FILE}.$(date '+%Y%m%d%H%M%S')"
fi

The Whole Flow ​

Log management is the last step in the chain of Linux concepts covered so far.

Separate accounts/groups
    └── Apply file permissions + ACL
            └── Control ownership/execute permission of monitor.sh
                    └── cron runs it every minute as agent-admin
                            └── Collect process/port/resource data
                                    └── Write to /var/log/agent-app/monitor.log
                                            └── Manage size with logrotate

SSH security and the firewall are a layer outside this flow that controls outside access itself.

Summary ​

  • Logs are kept to trace when a failure happened and what state the system was in.
  • >> appends, > overwrites.
  • Manage size with logrotate (size 10M, rotate 10, compress, etc.) or implement it directly in the script (if the file is 10MB or more, mv it with a timestamp attached).
  • Whole flow: separate accounts/groups → permissions + ACL → control monitor.sh permissions → cron runs every minute → collect → write to monitor.log → logrotate. SSH and the firewall control outside access from outside that flow.

Source: Codyssey-B1/B4-1