Complete reference for all public functions in the bash-logger module.
- Overview
- Initialization Functions
- Logging Functions
- Runtime Configuration Functions
- Public Constants
- Internal Functions
- Related Documentation
This document provides a complete reference for all public functions in bash-logger. Functions are organized by category:
- Initialization - Set up the logger
- Logging - Output log messages at different severity levels
- Runtime Configuration - Change settings after initialization
Note: Functions prefixed with underscore (_) are internal implementation details and should not be called
directly by consuming scripts.
Initialize the logging system with optional configuration.
Syntax:
init_logger [options]Options:
| Option | Short | Description | Default |
|---|---|---|---|
--level LEVEL |
-d |
Set log level (DEBUG, INFO, WARN, ERROR, etc.) | INFO |
--log FILE |
-l |
Write logs to file | (none) |
--quiet |
-q |
Disable console output | false |
--verbose |
-v |
Enable DEBUG level logging | false |
--journal |
-j |
Enable system journal logging | false |
--tag TAG |
-t |
Set journal tag (validated, see below) | (script) |
--facility FACILITY |
-F |
Set syslog facility for journal logging | daemon |
--utc |
-u |
Use UTC timestamps instead of local time | false |
--format FORMAT |
-f |
Set log message format | (see below) |
--color |
Force color output | auto | |
--no-color |
Disable color output | auto | |
--config FILE |
-c |
Load configuration from INI file | (none) |
--stderr-level LEVEL |
-e |
Messages at/above this level go to stderr | ERROR |
--unsafe-allow-newlines |
-U |
Allow newlines in log messages (unsafe) | false |
--unsafe-allow-ansi-codes |
-A |
Keep escape sequences and other control characters (unsafe) | false |
--max-line-length LENGTH |
Max message length before formatting | 4096 | |
--max-journal-length LENGTH |
Max message length for journal | 4096 |
Default Format:
%d [%l] [%s] %m
Format Variables:
%d- Date and time (YYYY-MM-DD HH:MM:SS)%z- Timezone (UTC or LOCAL)%l- Log level name (DEBUG, INFO, WARN, ERROR, etc.)%s- Script name%m- Log message
Returns:
0- Success1- Error (e.g., cannot create log file)
Examples:
# Basic initialization
init_logger
# Development mode
init_logger --verbose --color
# Production with file logging
init_logger --log "/var/log/myapp.log" --level INFO
# System service with journal
init_logger --journal --tag "myapp"
# Load from configuration file
init_logger --config /etc/myapp/logging.conf
# Custom format
init_logger --format "%d %z [%l] %m"
# Multiple options
init_logger --log "/var/log/app.log" --journal --tag "app" --level DEBUGSee Also:
Check if the system logger command is available and validated for journal logging.
Security: This function validates that the logger executable is located in a trusted system directory to prevent PATH manipulation attacks.
Syntax:
check_logger_availableReturns:
0- logger command is available and in a safe location1- logger command is not available or not in a trusted location
Trusted Locations:
/bin/logger/usr/bin/logger/usr/local/bin/logger/sbin/logger/usr/sbin/logger
Examples:
# Check before enabling journal logging
if check_logger_available; then
init_logger --journal
else
init_logger --log "/var/log/myapp.log"
fi
# Conditional journal logging
if check_logger_available; then
log_info "Journal logging is available"
else
log_warn "Journal logging not available, using file logging only"
fiNote: If logger is found in an unexpected location, a warning is displayed and the function returns 1. This is a security feature to prevent malicious logger substitution via PATH manipulation.
See Also:
All logging functions accept a single string parameter: the message to log.
Output a DEBUG level message (level 7).
Syntax:
log_debug "message"When to Use:
- Detailed debugging information
- Variable values during troubleshooting
- Function entry/exit points
- Loop iterations and conditions
Visibility:
- Hidden by default (only shown when log level is DEBUG)
- Use
--verboseor--level DEBUGto enable
Examples:
log_debug "Entering process_data function"
log_debug "Variable value: count=$count"
log_debug "Processing item $i of $total"See Also:
Output an INFO level message (level 6).
Syntax:
log_info "message"When to Use:
- General informational messages
- Script progress updates
- Successful operations
- Normal workflow events
Visibility:
- Shown by default (INFO is the default log level)
Examples:
log_info "Starting backup process"
log_info "Successfully processed 100 records"
log_info "Configuration loaded from file"See Also:
Output a NOTICE level message (level 5).
Syntax:
log_notice "message"When to Use:
- Normal but significant conditions
- Important milestones
- Configuration changes
- State transitions
Visibility:
- Shown by default
Examples:
log_notice "Application started in production mode"
log_notice "Cache cleared successfully"
log_notice "Switching to fallback database"See Also:
Output a WARN level message (level 4).
Syntax:
log_warn "message"When to Use:
- Warning conditions that don't prevent operation
- Deprecated feature usage
- Configuration issues that have defaults
- Approaching resource limits
Visibility:
- Shown by default
- Goes to stdout by default
Examples:
log_warn "Disk space is running low (85% used)"
log_warn "API rate limit approaching"
log_warn "Using deprecated configuration format"See Also:
Output an ERROR level message (level 3).
Syntax:
log_error "message"When to Use:
- Error conditions that may be recoverable
- Failed operations
- Unexpected conditions
- Exceptions that are caught and handled
Visibility:
- Shown by default
- Goes to stderr by default
Examples:
log_error "Failed to connect to database"
log_error "File not found: $filename"
log_error "Invalid input: expected number, got '$input'"See Also:
Output a CRITICAL level message (level 2).
Syntax:
log_critical "message"When to Use:
- Critical conditions requiring immediate attention
- System component failures
- Data corruption
- Security breaches
Visibility:
- Always shown
- Goes to stderr
Examples:
log_critical "Database corruption detected"
log_critical "Security certificate has expired"
log_critical "Out of memory - cannot continue"See Also:
Output an ALERT level message (level 1).
Syntax:
log_alert "message"When to Use:
- Action must be taken immediately
- Service outages
- Critical system failures requiring operator intervention
Visibility:
- Always shown
- Goes to stderr
Examples:
log_alert "Primary database is down - failover required"
log_alert "All API endpoints are unresponsive"
log_alert "Backup system has failed"See Also:
Output an EMERGENCY level message (level 0).
Syntax:
log_emergency "message"When to Use:
- System is completely unusable
- Imminent crash or data loss
- Unrecoverable errors
Visibility:
- Always shown
- Goes to stderr
Examples:
log_emergency "System is out of resources and must shut down"
log_emergency "Critical configuration error - cannot start"
log_emergency "Data integrity compromised - halting all operations"See Also:
Alias for log_emergency. Output a FATAL level message (level 0).
Syntax:
log_fatal "message"When to Use:
Same as log_emergency - provided for compatibility and readability.
Examples:
log_fatal "Fatal error: cannot recover"
log_fatal "System initialization failed"See Also:
Output an initialization message (shown at INFO level).
Syntax:
log_init "message"When to Use:
- Logging initialization events
- Component startup messages
- System bootstrap logging
Special Behavior:
- Not logged to journal (prevents initialization loops)
- Always shown regardless of log level
Examples:
log_init "Application starting - version 1.2.3"
log_init "Configuration loaded from /etc/myapp.conf"Output sensitive data to console only (never to file or journal).
Syntax:
log_sensitive "message"When to Use:
- Debugging with passwords or tokens
- Displaying API keys during troubleshooting
- Showing connection strings with credentials
Security Features:
- Never written to log files
- Never sent to system journal
- Only displayed on console (if console output is enabled)
- Useful for debugging without compromising security
Examples:
log_sensitive "Database password: $DB_PASS"
log_sensitive "API token: $API_TOKEN"
log_sensitive "Connection string: $CONNECTION_STRING"Even console-only logging can be risky. Use log_sensitive only when necessary, and never in production with console
output that could be captured or logged by terminal emulators or shell history.
See Also:
Log a single message using the normal routing (console and log file, if enabled) and also force it to be written to the system journal, regardless of the USE_JOURNAL setting.
This follows the same per-call override pattern as log_sensitive. It is intended for callers
that must guarantee journal delivery for a specific message while preserving normal console/file logging behavior, without enabling journal logging
globally.
Syntax:
log_to_journal LEVEL MESSAGEParameters:
LEVEL- Log level name:DEBUG,INFO,NOTICE,WARN,ERROR,CRITICAL,ALERT,EMERGENCY(aliasesWARNING,ERR,CRIT,EMERG,FATALare also accepted), or a numeric syslog level0–7.MESSAGE- The message to send to the journal.
Returns:
0- Success1- Unrecognised level name, wrong number of arguments, orloggercommand not available
Behaviour:
- Respects the current log level — if the resolved level value is above
CURRENT_LOG_LEVELthe message is silently suppressed with return code0, matching all other log functions. This suppression happens before any logger availability check, so no warning is emitted even whenloggeris not available. - Applies the same sanitisation (newline replacement, and removal of terminal control sequences and other control characters) and truncation rules as all other log functions. See Sensitive Data for what is removed.
- Console and file output follow the normal
CONSOLE_LOGandLOG_FILEsettings. - When
loggeris not available or fails validation (for example when the binary is missing, is outside the trusted system directories, or no longer matches the path validated earlier) and the message is at or aboveCURRENT_LOG_LEVEL, a warning is emitted to stderr and the function returns1rather than silently discarding the message, regardless of the value ofUSE_JOURNAL. - Only a
LOGGER_PATHthat validation locked (made readonly) is run. A value assigned any other way is refused. log_sensitivebehaviour is unaffected —log_to_journaldoes not change theskip_journallogic and cannot cause sensitive messages to reach the journal.
Examples:
# Force a critical audit event to the journal without enabling journal logging globally
log_to_journal CRITICAL "User 'root' logged in from $REMOTE_ADDR"
# Use alongside regular logging
init_logger --log /var/log/myapp.log
log_info "Normal file-only message"
log_to_journal NOTICE "Significant event that must reach the journal"
# Guard against unavailable logger
if ! log_to_journal ERROR "Deployment complete"; then
log_error "Could not write to system journal"
fiSee Also:
These functions allow you to change logger settings after initialization.
Change the minimum log level for displayed messages.
Syntax:
set_log_level LEVELParameters:
LEVEL- Level name (DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, ALERT, EMERGENCY) or numeric value (0-7)
Examples:
# Enable debug logging
set_log_level DEBUG
# Show only warnings and errors
set_log_level WARN
# Using numeric values
set_log_level 7 # DEBUG
set_log_level 3 # ERROR
# Conditional debug mode
if [[ "$DEBUG_MODE" == "true" ]]; then
set_log_level DEBUG
fiEffects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent log messages
See Also:
Change the log message format template.
Syntax:
set_log_format "format_string"Parameters:
format_string- Format template using variables:%d- Date and time%z- Timezone%l- Log level%s- Script name%m- Message
Examples:
# Minimal format
set_log_format "%m"
# Include timezone
set_log_format "%d %z [%l] %m"
# Custom separator
set_log_format "%l | %d | %m"
# JSON-like format
set_log_format '{"time":"%d","level":"%l","message":"%m"}'Effects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent log messages
See Also:
Switch between UTC and local time for timestamps.
Syntax:
set_timezone_utc BOOLEANParameters:
BOOLEAN-trueto use UTC,falseto use local time
Examples:
# Switch to UTC
set_timezone_utc true
# Switch back to local time
set_timezone_utc false
# Conditional timezone
if [[ "$ENVIRONMENT" == "production" ]]; then
set_timezone_utc true # Use UTC in production
fiEffects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent log messages
See Also:
Enable or disable system journal logging at runtime.
Syntax:
set_journal_logging BOOLEANParameters:
BOOLEAN-trueto enable,falseto disable
Returns:
0- Success1- Error (e.g., logger command not available when trying to enable)
Examples:
# Disable journal logging
set_journal_logging false
# Re-enable journal logging
set_journal_logging true
# Conditional journal logging
if check_logger_available; then
set_journal_logging true
else
log_warn "Journal logging not available"
fiEffects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent log messages
See Also:
Change the tag used for journal log entries.
Syntax:
set_journal_tag "tag"Parameters:
tag- String identifier for journal entries. It must not be empty or longer than 64 characters, and must not contain control characters or shell metacharacters. See Tag Rules
Returns:
0- The tag was changed1- The tag is invalid. A message explains why, and the previous tag is kept
Examples:
# Change tag for different components
set_journal_tag "database-sync"
# ... database operations ...
set_journal_tag "api-client"
# ... API operations ...
# Use process ID in tag
set_journal_tag "myapp-$$"
# Component-based tagging
set_journal_tag "myapp-${COMPONENT_NAME}"Effects:
- Logs a CONFIG message using the OLD tag, documenting the change
- Takes effect immediately for all subsequent journal log entries
See Also:
Change the syslog facility used for journal log entries.
Syntax:
set_syslog_facility FACILITYParameters:
FACILITY- One of:kern,user,mail,daemon,auth,syslog,lpr,news,uucp,cron,authpriv,ftp,local0,local1,local2,local3,local4,local5,local6,local7
Returns:
0- Success1- Invalid facility
Examples:
# Use an application-specific facility
set_syslog_facility local0
# Switch back to default
set_syslog_facility daemonEffects:
- Validates the facility name before applying it
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent journal log entries
See Also:
Change color output mode for console logging.
Syntax:
set_color_mode MODEParameters:
MODE- One of:auto- Auto-detect terminal color support (default)always- Force color outputnever- Disable color outputtrue,on,yes,1- Same asalwaysfalse,off,no,0- Same asnever
Examples:
# Force colors on
set_color_mode always
# Disable colors
set_color_mode never
# Auto-detect (default)
set_color_mode auto
# Conditional coloring
if [[ -t 1 ]]; then
set_color_mode always
else
set_color_mode never
fiEffects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent console output
Color Detection (auto mode):
- Checks
NO_COLORenvironment variable - Checks
CLICOLORandCLICOLOR_FORCEenvironment variables - Tests if stdout is a terminal
- Uses
tputto check terminal capabilities - Checks
TERMenvironment variable
See Also:
Enable or disable unsafe mode for newlines in log messages.
Warning: When enabled, newline sanitization is disabled and log injection becomes possible. Only use this when you control all log inputs and your log processing can handle embedded newlines safely.
Syntax:
set_unsafe_allow_newlines BOOLEANParameters:
BOOLEAN-trueto allow newlines,falseto sanitize them (default)
Examples:
# Enable unsafe mode (not recommended)
set_unsafe_allow_newlines true
# Restore secure default
set_unsafe_allow_newlines falseEffects:
- Logs a CONFIG message documenting the change
- Takes effect immediately for all subsequent log messages
See Also:
Enable or disable unsafe mode for ANSI escape codes in log messages.
Warning: When enabled, ANSI code stripping is disabled and terminal manipulation attacks become possible. Only use this when you control all log inputs and trust their source completely.
Syntax:
set_unsafe_allow_ansi_codes BOOLEANParameters:
BOOLEAN-trueto allow ANSI codes,falseto strip them (default)
Examples:
# Enable unsafe mode (not recommended)
set_unsafe_allow_ansi_codes true
# Restore secure default
set_unsafe_allow_ansi_codes falseEffects:
- Logs a CONFIG message documenting the change (in red when enabling unsafe mode as a warning)
- Takes effect immediately for all subsequent log messages
- Keeps escape sequences and the other control characters in messages while enabled
Security Considerations:
By default, bash-logger strips ANSI escape sequences from user input to prevent:
- Terminal display manipulation (clearing screen, cursor positioning)
- Window title changes for social engineering
- Visual spoofing attacks (fake error messages)
- Terminal emulator exploitation via crafted sequences
It also removes other control characters: the C0 controls other than newline, carriage return and tab (such as backspace and BEL), DEL, the C1 controls, U+2028 and U+2029, and the bidirectional formatting characters U+202A to U+202E and U+2066 to U+2069. Enabling this unsafe mode keeps all of them.
Library-generated ANSI codes for colors and formatting are preserved.
See Also:
These constants are available after sourcing logging.sh:
LOG_LEVEL_EMERGENCY=0 # Most severe
LOG_LEVEL_ALERT=1
LOG_LEVEL_CRITICAL=2
LOG_LEVEL_ERROR=3
LOG_LEVEL_WARN=4
LOG_LEVEL_NOTICE=5
LOG_LEVEL_INFO=6
LOG_LEVEL_DEBUG=7 # Least severe
LOG_LEVEL_FATAL=0 # Alias for EMERGENCYThese variables reflect the current logger configuration:
CURRENT_LOG_LEVEL # Current minimum log level (0-7)
LOG_FILE # Current log file path (empty if not logging to file)
CONSOLE_LOG # "true" or "false" - console output enabled
USE_JOURNAL # "true" or "false" - journal logging enabled
JOURNAL_TAG # Current journal tag
SYSLOG_FACILITY # Current syslog facility for journal entries
USE_UTC # "true" or "false" - UTC timestamps
LOG_FORMAT # Current format string
USE_COLORS # "auto", "always", or "never"
LOG_STDERR_LEVEL # Messages at/above this level go to stderr
SCRIPT_NAME # Name of the calling scriptBASH_LOGGER_VERSION # Version string (e.g., "1.0.0")Example:
source logging.sh
init_logger
echo "Logger version: $BASH_LOGGER_VERSION"
echo "Current log level: $CURRENT_LOG_LEVEL"
echo "Log file: ${LOG_FILE:-none}"
# Conditional logic based on settings
if [[ "$CURRENT_LOG_LEVEL" -ge "$LOG_LEVEL_DEBUG" ]]; then
echo "Debug mode is enabled"
fiThe following functions are prefixed with underscore (_) and are internal implementation details. They should not
be called directly by consuming scripts:
_detect_color_support- Detect terminal color capabilities_should_use_colors- Determine if colors should be used_should_use_stderr- Determine if message should go to stderr_parse_config_file- Parse INI configuration files_get_log_level_value- Convert level name to numeric value_get_log_level_name- Convert numeric value to level name_get_log_level_color- Get ANSI color code for level_get_syslog_priority- Map level to syslog priority_format_log_message- Format log message using template_log_to_console- Output formatted message to console_log_message- Core logging implementation
Note: Internal functions may change between versions without notice. Always use the public API functions documented above.
- Getting Started - Quick start guide
- Initialization - Detailed initialization options
- Log Levels - Complete log level reference
- Configuration - Configuration file format
- Runtime Configuration - Changing settings at runtime
- Formatting - Message format customization
- Journal Logging - System journal integration
- Output Streams - Stdout/stderr behavior
- Sensitive Data - Handling secrets safely
- Examples - Comprehensive code examples
- Troubleshooting - Common issues and solutions