A simple and versatile Bash logging utility that supports different log levels, optional timestamps, and optional file output.
The recommended approach is to use the grab script:
source $(grab github.com/shellib/log)This will fetch and source library.sh directly from GitHub. Once sourced, the log function becomes available in your shell.
# Source the log library.
source $(grab github.com/shellib/log)
# Log messages of various levels.
log DEBUG "Debug message." # Will show if LOG_THRESHOLD <= DEBUG
log INFO "Information message." # Will show if LOG_THRESHOLD <= INFO
log WARN "Warning message." # Will show if LOG_THRESHOLD <= WARN
log ERROR "Error message." # Always logged if threshold is ERROR or below-
Threshold-based Logging
Controlled via theLOG_THRESHOLDenvironment variable. Possible values areDEBUG,INFO,WARN,ERROR. Defaults toINFOif unset. -
Optional Log File
If theLOG_FILEenvironment variable is set, all log messages are appended to the specified file. Otherwise, logs are printed to stdout or stderr (for errors). -
Timestamps
To include timestamps in your logs, pass-tor--with-timestampsas the first argument to thelogfunction. For example:log -t INFO "Starting the program..."Timestamps are in the format:
YYYY-MM-DD HH:MM:SS. -
DRY_RUN Mode
IfDRY_RUNis set totrue, each log line will be prefixed with[DRY_RUN]. This can be useful for simulating actions without performing them.
-
LOG_THRESHOLD
Sets the minimum level to log. Valid values:DEBUG,INFO,WARN,ERROR. Defaults toINFO. -
LOG_FILE
If specified, log messages go to this file (appended). Otherwise, logs go to terminal output. -
DRY_RUN
Iftrue,[DRY_RUN]is added to each log line.
log [FLAGS] LEVEL MESSAGE
Where:
FLAGScan be-tor--with-timestamps.LEVELis one ofDEBUG,INFO,WARN,ERROR.MESSAGEis the text to log.
Example:
# with timestamps
log --with-timestamps INFO "Some info message."
# regular usage
log ERROR "Badness happened!"