Logging Output in Shell Scripts: 3 Practical Examples

Explore three practical examples of logging output in shell scripts to enhance your scripting skills.
By Jamie

Introduction to Logging Output in Shell Scripts

Logging output in shell scripts is crucial for monitoring, debugging, and maintaining scripts effectively. By capturing important events, errors, and informational messages, developers can trace the execution flow and identify issues. Here are three diverse, practical examples that showcase how to implement logging in shell scripts.

Example 1: Simple Logging to a File

Context

This example demonstrates how to log messages to a specific log file. This is useful in scripts that perform repetitive tasks, allowing you to keep track of execution details over time.

#!/bin/bash

LOGFILE="script.log"

## Function to log messages
log_message() {
    echo "
\((date '+%Y-%m-%d %H:%M:%S') - \)1" >> "$LOGFILE"
}

## Main script execution
log_message "Script started"

## Simulating some operations
for i in {1..5}; do
    log_message "Processing item $i"
    sleep 1  # Simulate a task
    log_message "Completed item $i"
done

log_message "Script ended"

Notes

  • The log_message function formats log entries with a timestamp and appends them to the specified log file.
  • You can customize the log file path by changing the LOGFILE variable.

Example 2: Logging with Error Handling

Context

In this example, we’ll log error messages when a command fails. This is particularly useful for scripts that perform critical tasks, ensuring that failures are documented for later review.

#!/bin/bash

LOGFILE="error.log"

## Function to log error messages
log_error() {
    echo "
\((date '+%Y-%m-%d %H:%M:%S') - ERROR: \)1" >> "$LOGFILE"
}

## A sample command that might fail
command_to_run() {
#    # Simulating a command that fails
    false
}

## Main script execution
echo "Starting command..."
if ! command_to_run; then
    log_error "Command failed"
fi
echo "Script completed"

Notes

  • This script checks the exit status of a command using if !, logging an error message if the command fails.
  • Error logs are separated from regular logs, making it easier to identify issues.

Example 3: Logging with Dynamic Log Levels

Context

This example introduces dynamic log levels, allowing users to control the verbosity of the logging output. This can be particularly useful in larger scripts where you may want detailed logs during development and minimal logs in production.

#!/bin/bash

LOGFILE="dynamic.log"
LOG_LEVEL="INFO"

## Function to log messages based on log level
log_message() {
    local level="$1"
    shift
    if [[ "\(level" == "DEBUG" && "\)LOG_LEVEL" == "DEBUG" ]] || [[ "\(level" == "INFO" ]] || [[ "\)level" == "ERROR" ]]; then
        echo "
\((date '+%Y-%m-%d %H:%M:%S') - \)level: \(@" >> "\)LOGFILE"
    fi
}

## Main script execution
log_message "INFO" "Starting script"
log_message "DEBUG" "This is a debug message"
log_message "INFO" "Performing an important task"

## Simulating task completion
if true; then
    log_message "INFO" "Task completed successfully"
else
    log_message "ERROR" "Task failed"
fi
log_message "INFO" "Ending script"

Notes

  • This script allows you to set the LOG_LEVEL variable to control the output. Set it to DEBUG for detailed logs.
  • Adjust the logic in log_message to manage log levels as per your needs, allowing for more granular control over logging output.