Post

Bash Tutorials: How To Create Readable Log Helpers

Learn how to create log functions that make your scripts more readable and easier to debug.

Bash Tutorials: How To Create Readable Log Helpers

When you are writing Bash scripts, having a clear and consistent way to log messages is crucial. Good logging makes scripts easier to understand, debug, and maintain.

At a minimum, every log entry should include:

  • Log Level (e.g., INFO, ERROR)
  • Timestamp (when the message occurred)
  • Message (what happened)

Additionally, debug messages should only appear if a debug flag is enabled. This keeps your logs clean during normal execution but detailed when needed.

Hereโ€™s a simple and effective set of logging functions you can add to the beginning of your Bash scripts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# ------------------------------------------------------------------------------
# Generic Logging Functions
# ------------------------------------------------------------------------------
log() {
  local level="$1"
  shift  # Remove the level parameter from $@
  echo -e "[$level] $(date '+%Y-%m-%d %H:%M:%S') $*" >&2
}

log_success() {
  log "SUCCESS" "โœ… $*"
}

log_info() {
  log "INFO" "โ„น๏ธ  $*"
}

log_debug() {
  if [ "$IS_DEBUG_ENABLED" == "true" ]; then
    log "DEBUG" "๐Ÿ” $*"
  fi
}

log_error() {
  log "ERROR" "โŒ $*"
}

log_warning() {
  log "WARNING" "โš ๏ธ  $*"
}

How to Use

Once you include these functions, you can log events like this:

1
2
3
4
5
6
7
# Example usage in your script

log_success "Script started successfully."
log_info "Processing file: $FILE"
log_debug "Current working directory: $PWD"
log_error "Failed to process file: $FILE"
log_warning "Disk space is running low."

Example Output

If you run the above script, your console output would look like this:

1
2
3
4
5
[SUCCESS] โœ… 2025-03-05 23:29:29 Script started successfully.
[INFO] โ„น๏ธ 2025-03-05 23:29:29 Processing file: /Users/mehmet/Desktop/test.txt
[DEBUG] ๐Ÿ” 2025-03-05 23:29:29 Current working directory: /Users/mehmet/Desktop
[ERROR] โŒ 2025-03-05 23:29:29 Failed to process file: /Users/mehmet/Desktop/test.txt
[WARNING]โš ๏ธ 2025-03-05 23:29:29 Disk space is running low.

As you can see:

  • The log level appears first in brackets.
  • The timestamp shows when the message was logged.
  • The message follows with an optional emoji for better visibility.

This simple structure makes it much easier to debug and understand whatโ€™s happening inside your scripts, especially during complex operations.


If you have any questions or suggestions, feel free to reach out!

Happy logging! ๐Ÿ“ƒ

โ˜• Support My Work

If you found this post helpful and want to support more content like this, you can buy me a coffee!

Your support helps me continue creating useful articles and tips for fellow developers. Thank you! ๐Ÿ™

This post is licensed under CC BY 4.0 by the author.