85 lines
2.3 KiB
Bash

#!/usr/bin/env bash
if [[ -n "${ATLAS_LOGGING_SH_LOADED:-}" ]]; then
return 0
fi
ATLAS_LOGGING_SH_LOADED=1
ATLAS_LOG_FILE="${ATLAS_LOG_FILE:-}"
ATLAS_LOG_TO_FILE=0
atlas_timestamp() {
date -u '+%Y-%m-%dT%H:%M:%SZ'
}
atlas_log_line() {
local level="$1"
shift
local message="$*"
local line
line="$(printf '%s [%s] %s' "$(atlas_timestamp)" "$level" "$message")"
printf '%s\n' "$line"
if [[ "${ATLAS_LOG_TO_FILE}" == "1" && -n "${ATLAS_LOG_FILE}" ]]; then
printf '%s\n' "$line" >>"${ATLAS_LOG_FILE}" 2>/dev/null || ATLAS_LOG_TO_FILE=0
fi
}
atlas_log_info() {
atlas_log_line "INFO" "$@"
}
atlas_log_warn() {
atlas_log_line "WARN" "$@"
}
atlas_log_error() {
atlas_log_line "ERROR" "$@" >&2
}
atlas_log_ok() {
atlas_log_line "OK" "$@"
}
atlas_log_verbose() {
if [[ "${ATLAS_VERBOSE:-0}" == "1" ]]; then
atlas_log_line "DEBUG" "$@"
fi
}
atlas_init_log_file() {
local log_dir="$1"
local name="${2:-${ATLAS_SCRIPT_NAME:-atlas}}"
local timestamp
timestamp="$(date -u '+%Y%m%dT%H%M%SZ')"
ATLAS_LOG_FILE="${log_dir}/${name}-${timestamp}.log"
if [[ "${ATLAS_DRY_RUN:-0}" == "1" ]]; then
atlas_log_info "Dry-run mode: would initialise log file ${ATLAS_LOG_FILE}"
return 0
fi
if [[ ! -d "$log_dir" ]]; then
if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
sudo -n install -d -m 0750 -o "$(id -u)" -g "$(id -g)" "$log_dir" 2>/dev/null || {
atlas_log_warn "File logging disabled; cannot create ${log_dir}"
return 0
}
else
atlas_log_warn "File logging disabled; ${log_dir} does not exist and sudo is unavailable"
return 0
fi
fi
if [[ -w "$log_dir" ]]; then
: >"${ATLAS_LOG_FILE}" 2>/dev/null && chmod 0640 "${ATLAS_LOG_FILE}" 2>/dev/null && ATLAS_LOG_TO_FILE=1 || ATLAS_LOG_TO_FILE=0
elif command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
sudo -n touch "${ATLAS_LOG_FILE}" 2>/dev/null && sudo -n chown "$(id -u):$(id -g)" "${ATLAS_LOG_FILE}" 2>/dev/null && sudo -n chmod 0640 "${ATLAS_LOG_FILE}" 2>/dev/null && ATLAS_LOG_TO_FILE=1 || ATLAS_LOG_TO_FILE=0
fi
if [[ "${ATLAS_LOG_TO_FILE}" == "1" ]]; then
atlas_log_info "Logging to ${ATLAS_LOG_FILE}"
else
atlas_log_warn "File logging unavailable; continuing with console logging"
fi
}