Bash Tutorials: How To Create Readable Log Helpers
Learn how to create log functions that make your scripts more readable and easier to debug.
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! ๐