Custom Logger in Bash

While writing scripts in Bash, adding some nice, reusable functions for logging.

#!/bin/bash

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Error handling
handle_error() {
    echo -e "${RED}Error: $1${NC}" >&2
    cleanup
    exit 1
}

# Logging function
log() {
    local level=$1
    local message=$2
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo -e "[$timestamp] [$level] $message"
    case $level in
        "ERROR")   echo -e "${RED}$message${NC}" >&3 ;;
        "WARNING") echo -e "${YELLOW}$message${NC}" >&3 ;;
        "INFO")    echo -e "${BLUE}$message${NC}" >&3 ;;
        "SUCCESS") echo -e "${GREEN}$message${NC}" >&3 ;;
    esac
}

...
<other functions>
...

# Check API health
log "INFO" "Checking API health..."
health_response=$(api_call "GET" "/health")
if ! echo "$health_response" | python3 -c "import sys, json; sys.exit(0 if json.load(sys.stdin)['status'] == 'success' else 1)" 2>/dev/null; then
    handle_error "API is not healthy"
fi
log "SUCCESS" "API is healthy"

Here is how the above looks like:

Code explanation

Here’s a breakdown of each section of the Bash script

Color Definitions

The script begins by defining several color codes for output messages. These colors enhance visibility and make it easier to distinguish between different types of log messages when the script is executed. The variables GREEN, BLUE, RED, and YELLOW are assigned ANSI escape sequences that correspond to specific colors in the terminal. The variable NC (No Color) is used to reset the text color back to default after colored outputs.

Error Handling Function

The next section defines the handle_error() function, which centralizes error handling within the script. This function takes an error message as an argument, prints it in red for emphasis, calls a cleanup function (if defined), and then exits the script with a status code of 1 indicating failure. This approach ensures that any errors encountered during execution are handled consistently and visibly.

Logging Function

Following error handling, there is a logging function named log(). This reusable function accepts two parameters: the severity level (e.g., ERROR, WARNING, INFO, SUCCESS) and a message to log. It timestamps each log entry using the current date and time before printing it out with appropriate formatting based on its severity level. The logs are color-coded according to their type—errors appear in red, warnings in yellow, informational messages in blue, and successes in green—making it easy for users to quickly assess system status at a glance.

API Health Check

The main operational part of this script involves checking API health through a dedicated function called check_api_health(). Within this segment, an informational log entry indicates that an API health check is being performed. The script makes an HTTP GET request to /health using another custom-defined function (api_call) and captures its response. It then checks if the JSON response contains a successful status; if not or if there’s any issue parsing it (handled via exceptions), it triggers the previously defined error handler with an appropriate message about API unhealthiness.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.