0
0
Bash Scriptingscripting~5 mins

Logging framework in Bash Scripting

Choose your learning style9 modes available
Introduction

Logging helps you keep track of what your script is doing. It records messages that tell you about events or errors.

When you want to see what happened during a script run to find problems.
When you want to save important messages for later review.
When you want to monitor script progress in real time.
When you want to separate normal messages from error messages.
When you want to keep a history of script activity for auditing.
Syntax
Bash Scripting
log() {
  local level="$1"
  shift
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*"
}

This function prints a timestamp, a log level, and your message.

You can call it with levels like INFO, WARN, or ERROR.

Examples
Logs an informational message that the script started.
Bash Scripting
log INFO "Script started"
Logs an error message about a missing file.
Bash Scripting
log ERROR "File not found"
Logs a warning about disk space.
Bash Scripting
log WARN "Low disk space"
Sample Program

This script defines a simple logging function. It logs when the script starts and ends. It checks if a file exists and logs an error if not.

Bash Scripting
#!/bin/bash

log() {
  local level="$1"
  shift
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*"
}

log INFO "Script started"
if [ ! -f "/tmp/testfile" ]; then
  log ERROR "File /tmp/testfile not found"
else
  log INFO "File /tmp/testfile exists"
fi
log INFO "Script ended"
OutputSuccess
Important Notes

You can redirect log output to a file by running your script like: ./script.sh > script.log

Use different log levels to filter messages later.

Make sure your system clock is correct for accurate timestamps.

Summary

Logging records important messages during script execution.

A simple logging function prints timestamp, level, and message.

Use logging to find errors and understand script behavior.