The init_logger function is the entry point for configuring the Bash Logging Module. It must be called before using
any logging functions.
- Basic Initialization
- Initialization Options
- Common Initialization Patterns
- Combining Options
- Return Codes
- Initialization Best Practices
- Examples by Use Case
- Related Documentation
# Source the module
source /path/to/logging.sh
# Initialize with defaults
init_loggerThe init_logger function accepts the following options:
| Option | Description |
|---|---|
-c, --config FILE |
Load configuration from an INI file (CLI args override config values) |
-l, --log, --logfile, --log-file, --file FILE |
Specify a log file to write logs to |
-n, --name, --script-name NAME |
Set custom script name for log messages (overrides auto-detection) |
-q, --quiet |
Disable console output |
-v, --verbose, --debug |
Set log level to DEBUG (most verbose) |
-d, --level LEVEL |
Set log level (DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, ALERT, EMERGENCY or 0-7) |
-e, --stderr-level LEVEL |
Set minimum level for stderr output (default: ERROR) |
-f, --format FORMAT |
Set custom log format |
-u, --utc |
Use UTC time instead of local time |
-j, --journal |
Enable logging to systemd journal |
-t, --tag TAG |
Set custom tag for journal logs (default: script name) |
--color, --colour |
Explicitly enable color output (default: auto-detect) |
--no-color, --no-colour |
Disable color output |
-U, --unsafe-allow-newlines |
Allow newlines in log messages (not recommended; disables sanitization) |
-A, --unsafe-allow-ansi-codes |
Allow ANSI escape codes in log messages (not recommended; disables sanitization) |
--max-line-length LENGTH |
Max message length before formatting for console/file output (0 = unlimited) |
--max-journal-length LENGTH |
Max message length before formatting for journal output (0 = unlimited) |
# Uses INFO level, console output with color auto-detection
init_loggerDefault behavior:
- Log level: INFO
- Output: Console (stdout/stderr)
- Colors: Auto-detected (enabled for TTY)
- Format:
%d [%l] [%s] %m - Timezone: Local time
# Log to file with INFO level
init_logger --log "/var/log/myapp.log"
# Log to file with DEBUG level
init_logger --log "/var/log/myapp.log" --verbose
# Log to file only (no console output)
init_logger --log "/var/log/myapp.log" --quiet# Enable DEBUG level logging
init_logger --verbose
# Alternative syntax
init_logger --debug
init_logger --level DEBUG# Enable systemd journal logging
init_logger --journal
# Journal with custom tag
init_logger --journal --tag "myapp"
# Journal and file logging
init_logger --journal --log "/var/log/myapp.log" --tag "myapp"# Load all settings from config file
init_logger --config /etc/myapp/logging.conf
# Config file with CLI overrides (CLI takes precedence)
init_logger --config logging.conf --level DEBUG
# Multiple overrides
init_logger --config logging.conf --level WARN --color --log /tmp/app.logSee Configuration for details on configuration files.
# Custom format with all placeholders
init_logger --format "[%l] %d %z [%s] %m"
# Minimal format
init_logger --format "%l: %m"See Formatting for format options.
# Use UTC instead of local time
init_logger --utc
# UTC with custom format showing timezone
init_logger --utc --format "%d %z [%l] %m"# Force colors on (even when not a TTY)
init_logger --color
# Disable colors
init_logger --no-color
# Auto-detect (default)
init_logger # Colors enabled if stdout is a TTYBy default, the logger auto-detects the calling script's name. This works well for most scenarios, but may return
"unknown" when called from shell RC files or other non-standard contexts. Use the -n option to set a custom name:
# Set a custom script name
init_logger --name "my-startup-script"
# Useful for shell RC files
init_logger --name "bashrc" --level INFO
# Alternative syntax
init_logger --script-name "my-app"The script name appears in log messages where %s is used in the format string.
# Default: ERROR and above to stderr
init_logger
# Send WARN and above to stderr
init_logger --stderr-level WARN
# Send everything to stderr
init_logger --stderr-level DEBUG
# Only EMERGENCY to stderr
init_logger --stderr-level EMERGENCYSee Output Streams for details.
You can combine multiple options to create complex configurations:
init_logger \
--verbose \
--color \
--log "/tmp/dev.log" \
--format "[%l] %d - %m"init_logger \
--log "/var/log/myapp/app.log" \
--journal \
--tag "myapp" \
--level INFO \
--utc \
--stderr-level WARNinit_logger \
--level DEBUG \
--no-color \
--stderr-level DEBUG# All logs to stderr, stdout free for program output
init_logger \
--level INFO \
--stderr-level DEBUG \
--colorThe init_logger function returns:
0- Successful initialization1- Error during initialization
# Basic error handling
if ! init_logger --log "/var/log/myapp.log"; then
echo "ERROR: Failed to initialize logger" >&2
exit 1
fi
# Detailed error handling
if ! init_logger --log "/var/log/myapp.log" --journal --tag "myapp"; then
echo "ERROR: Logger initialization failed" >&2
echo "Check that:" >&2
echo " - Log directory exists and is writable" >&2
echo " - 'logger' command is available (for journal logging)" >&2
exit 1
fiLog file cannot be created:
# Check directory exists and is writable
init_logger --log "/nonexistent/dir/app.log" # Returns 1Invalid log level:
# Valid: DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, ALERT, EMERGENCY, 0-7
init_logger --level INVALID # Uses default (INFO)Call init_logger immediately after sourcing the module:
#!/bin/bash
source /path/to/logging.sh
init_logger --log "/var/log/myapp.log"
# Now safe to use logging
log_info "Script started"Always check if initialization succeeded:
if ! init_logger --log "$LOG_FILE"; then
echo "Failed to initialize logging" >&2
exit 1
fiInstead of long command lines, use config files:
# Clean and maintainable
init_logger --config /etc/myapp/logging.conf
# Instead of this
init_logger --log "/var/log/myapp.log" --journal --tag "myapp" \
--level INFO --utc --format "%d %z [%l] %m" --stderr-level WARNFor scripts that use config files, allow CLI overrides:
#!/bin/bash
source /path/to/logging.sh
LOG_LEVEL="INFO"
# Parse arguments for log level override
while [[ "$#" -gt 0 ]]; do
case $1 in
--debug) LOG_LEVEL="DEBUG"; shift ;;
*) shift ;;
esac
done
# Initialize with config file, override level if specified
init_logger --config /etc/myapp/logging.conf --level "$LOG_LEVEL"Use different configurations for different environments:
#!/bin/bash
source /path/to/logging.sh
ENV="${APP_ENV:-production}"
case "$ENV" in
development)
init_logger --verbose --color
;;
testing)
init_logger --level DEBUG --no-color
;;
production)
init_logger --config /etc/myapp/logging.conf
;;
esacbash-logger uses global variables that are initialized with default values when the module is sourced.
These variables can be modified after sourcing but before calling init_logger().
Understanding this behavior is important to avoid unexpected configuration:
How it works:
# Variables are reset to defaults when sourcing
source /path/to/logging.sh # LOG_FILE="", USE_COLORS="auto", etc.
# You can override defaults BEFORE calling init_logger
LOG_FILE="/tmp/my.log"
USE_COLORS="never"
init_logger # Uses the modified values
# Or pass them as arguments (cleaner approach)
source /path/to/logging.sh
init_logger --log "/tmp/my.log" --colors neverPotential Issues:
- Unintended configuration if parent shell/environment sets these variables
- In multi-user systems, one user could affect another's logging by exporting variables
- Automation/CI systems might unexpectedly override logging configuration
Best Practices:
Make your initialization explicit and intentional:
#!/bin/bash
# GOOD: Explicit configuration via init_logger arguments
source /path/to/logging.sh
init_logger --log "/var/log/myapp.log" --level INFO
# GOOD: Use configuration files for complex setups
init_logger --config /etc/myapp/logging.conf
# CAUTION: This can be affected by parent environment
source /path/to/logging.sh
init_logger # May use LOG_FILE from environmentFor secure or critical applications, avoid relying on inherited environment variables:
#!/bin/bash
# Explicitly unset any pre-existing bash-logger variables to ensure clean state
unset LOG_FILE USE_COLORS LOG_FORMAT CURRENT_LOG_LEVEL LOG_STDERR_LEVEL SCRIPT_NAME USE_JOURNAL
source /path/to/logging.sh
# Now initialize with only explicit configuration
init_logger --log "/secure/location/app.log" --level WARN#!/bin/bash
source /path/to/logging.sh
init_logger
log_info "Hello, World!"#!/bin/bash
source /path/to/logging.sh
init_logger --log "/tmp/script.log" --level INFO
log_info "Logging to file"#!/bin/bash
source /path/to/logging.sh
init_logger --journal --tag "myservice" --level INFO --utc
log_info "Service started"#!/bin/bash
source /path/to/logging.sh
init_logger --verbose --color --log "/tmp/debug.log"
log_debug "Debug information"When sourcing the logger from shell RC files (.bashrc, .zshrc), auto-detection may fail. Use --name to set a
meaningful identifier:
# In ~/.bashrc or ~/.zshrc
source /path/to/logging.sh
init_logger --name "bashrc" --level INFO --log "$HOME/.local/log/shell.log"
log_info "Shell session started"- Configuration - Using configuration files
- Log Levels - Understanding log levels
- Formatting - Custom log formats
- Output Streams - Stdout/stderr configuration
- Journal Logging - Systemd journal integration
- Getting Started - Quick start guide