Skip to content

Latest commit

 

History

History
1109 lines (746 loc) · 24.5 KB

File metadata and controls

1109 lines (746 loc) · 24.5 KB

API Reference

Complete reference for all public functions in the bash-logger module.

Table of Contents

Overview

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.

Initialization Functions

init_logger

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 (script)
--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 Allow ANSI escape codes in log messages (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 - Success
  • 1 - 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 DEBUG

See Also:


check_logger_available

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_available

Returns:

  • 0 - logger command is available and in a safe location
  • 1 - 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"
fi

Note: 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:


Logging Functions

All logging functions accept a single string parameter: the message to log.

log_debug

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 --verbose or --level DEBUG to enable

Examples:

log_debug "Entering process_data function"
log_debug "Variable value: count=$count"
log_debug "Processing item $i of $total"

See Also:


log_info

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:


log_notice

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:


log_warn

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:


log_error

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:


log_critical

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:


log_alert

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:


log_emergency

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:


log_fatal

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:


log_init

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"

log_sensitive

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"

⚠️ Warning:

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_to_journal

Send a single message directly 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 without enabling journal logging globally.

Syntax:

log_to_journal LEVEL MESSAGE

Parameters:

  • LEVEL - Log level name: DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, ALERT, EMERGENCY (aliases WARNING, ERR, CRIT, EMERG, FATAL are also accepted), or a numeric syslog level 0–7.
  • MESSAGE - The message to send to the journal.

Returns:

  • 0 - Success
  • 1 - Unrecognised level name, wrong number of arguments, or logger command not available

Behaviour:

  • Respects the current log level — if the resolved level value is above CURRENT_LOG_LEVEL the message is silently suppressed, matching all other log functions.
  • Applies the same sanitisation (newline and ANSI stripping) and truncation rules as all other log functions.
  • Console and file output follow the normal CONSOLE_LOG and LOG_FILE settings.
  • When logger is not available and USE_JOURNAL is false, a warning is emitted to stderr and the function returns 1 rather than silently discarding the message.
  • log_sensitive behaviour is unaffected — log_to_journal does not change the skip_journal logic 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"
fi

See Also:


Runtime Configuration Functions

These functions allow you to change logger settings after initialization.

set_log_level

Change the minimum log level for displayed messages.

Syntax:

set_log_level LEVEL

Parameters:

  • 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
fi

Effects:

  • Logs a CONFIG message documenting the change
  • Takes effect immediately for all subsequent log messages

See Also:


set_log_format

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:


set_timezone_utc

Switch between UTC and local time for timestamps.

Syntax:

set_timezone_utc BOOLEAN

Parameters:

  • BOOLEAN - true to use UTC, false to 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
fi

Effects:

  • Logs a CONFIG message documenting the change
  • Takes effect immediately for all subsequent log messages

See Also:


set_journal_logging

Enable or disable system journal logging at runtime.

Syntax:

set_journal_logging BOOLEAN

Parameters:

  • BOOLEAN - true to enable, false to disable

Returns:

  • 0 - Success
  • 1 - 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"
fi

Effects:

  • Logs a CONFIG message documenting the change
  • Takes effect immediately for all subsequent log messages

See Also:


set_journal_tag

Change the tag used for journal log entries.

Syntax:

set_journal_tag "tag"

Parameters:

  • tag - String identifier for journal entries

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:


set_color_mode

Change color output mode for console logging.

Syntax:

set_color_mode MODE

Parameters:

  • MODE - One of:
    • auto - Auto-detect terminal color support (default)
    • always - Force color output
    • never - Disable color output
    • true, on, yes, 1 - Same as always
    • false, off, no, 0 - Same as never

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
fi

Effects:

  • Logs a CONFIG message documenting the change
  • Takes effect immediately for all subsequent console output

Color Detection (auto mode):

  • Checks NO_COLOR environment variable
  • Checks CLICOLOR and CLICOLOR_FORCE environment variables
  • Tests if stdout is a terminal
  • Uses tput to check terminal capabilities
  • Checks TERM environment variable

See Also:


set_unsafe_allow_newlines

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 BOOLEAN

Parameters:

  • BOOLEAN - true to allow newlines, false to sanitize them (default)

Examples:

# Enable unsafe mode (not recommended)
set_unsafe_allow_newlines true

# Restore secure default
set_unsafe_allow_newlines false

Effects:

  • Logs a CONFIG message documenting the change
  • Takes effect immediately for all subsequent log messages

See Also:


set_unsafe_allow_ansi_codes

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 BOOLEAN

Parameters:

  • BOOLEAN - true to allow ANSI codes, false to strip them (default)

Examples:

# Enable unsafe mode (not recommended)
set_unsafe_allow_ansi_codes true

# Restore secure default
set_unsafe_allow_ansi_codes false

Effects:

  • Logs a CONFIG message documenting the change (in red when enabling unsafe mode as a warning)
  • Takes effect immediately for all subsequent log messages
  • Affects _strip_ansi_codes() behavior in _sanitize_log_message()

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

Library-generated ANSI codes for colors and formatting are preserved.

See Also:


Public Constants

These constants are available after sourcing logging.sh:

Log Level Constants

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 EMERGENCY

Current Settings

These 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
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 script

Version

BASH_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"
fi

Internal Functions

The 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.


Related Documentation