BASH

Timestamped Logging with Simple Log Rotation

Implement basic timestamped logging to a file in bash, including a simple rotation mechanism to keep log file sizes manageable.

#!/bin/bash

# Simple timestamped logger with basic log rotation

LOG_FILE="/var/log/my_app/app.log"
MAX_LOG_SIZE_KB=1024 # Rotate log if it exceeds 1MB
BACKUP_COUNT=3       # Keep this many old log files

# Ensure log directory exists
mkdir -p "$(dirname "$LOG_FILE")"

# Function to log messages with a timestamp
log_message() {
  local MESSAGE="$*"
  echo "$(date +'%Y-%m-%d %H:%M:%S') - $MESSAGE" | tee -a "$LOG_FILE"
}

# Function for simple log rotation
rotate_log() {
  if [ -f "$LOG_FILE" ]; then
    CURRENT_SIZE=$(du -k "$LOG_FILE" | cut -f1)
    if [ "$CURRENT_SIZE" -gt "$MAX_LOG_SIZE_KB" ]; then
      log_message "Log file $LOG_FILE (Size: ${CURRENT_SIZE}KB) exceeding ${MAX_LOG_SIZE_KB}KB. Rotating..."

      # Remove oldest backup
      if [ -f "${LOG_FILE}.${BACKUP_COUNT}" ]; then
        rm "${LOG_FILE}.${BACKUP_COUNT}"
      fi

      # Shift existing backups
      for (( i=BACKUP_COUNT-1; i>=1; i-- )); do
        if [ -f "${LOG_FILE}.$i" ]; then
          mv "${LOG_FILE}.$i" "${LOG_FILE}.$(($i+1))"
        fi
      done

      # Move current log to first backup
      mv "$LOG_FILE" "${LOG_FILE}.1"
      log_message "Log rotated. New log started."
    fi
  fi
}

# Example usage:
log_message "Script started."
rotate_log

for i in {1..5}; do
  log_message "Processing item $i..."
  sleep 0.1
  rotate_log # Check and rotate after each significant operation
done

log_message "Script finished."
rotate_log # Final check and rotation
How it works: This script provides a basic logging mechanism for bash applications, writing timestamped messages to a specified log file. It includes a simple log rotation feature that checks the log file size. If it exceeds a predefined limit, it renames the current log file to a backup (e.g., `app.log.1`), shifts older backups, and ensures that only a set number of backup files are kept, preventing logs from consuming excessive disk space. Messages are also echoed to `stdout` via `tee`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs