bash - 将STDERR重定向到日志功能

时间:2016-04-04 05:00:41

标签: bash

我有一个日志功能:

log() {
    if [[ "$#" -ne 2 ]];then
        printf "[%s] %s\n" 'error' 'log function requires two arguments'
        printf "%s\n" 'usage: log [level] "message"'
        printf "%s\n" 'e.g: log error "this is my error"'
        exit 1
    elif [[ "$1" == 'info' ]]; then
        printf "[%s] %s: %s %s\n" "info" "$(basename $0)" "$curr_date" "${2}"  &> >(tee -a "$log_file")
    elif [[ "$1" == 'warn' ]]; then
        printf "[%s] %s: %s %s\n" "warn" "$(basename $0)" "$curr_date" "${2}"  &> >(tee -a "$log_file")
    elif [[ "$1" == 'error' ]]; then
        printf "[%s] %s: %s\n" "error" "$(basename $0)" "$curr_date" "${2}"  &> >(tee -a "$log_file")
    elif [[ "$1" == 'debug' ]]; then
        printf "[%s] %s: %s %s\n" "debug" "$(basename $0)" "$curr_date" "${2}"  &> >(tee -a "$log_file")
    else
        printf "[%s] %s %s\n" 'error' 'unable to log with level' "'${1}'"
        printf "%26s '%s' '%s' '%s' '%s'\n" 'allowed levels are' 'info' 'warn' 'error' 'debug'
    fi
}

这是在一个外部文件中,并且源于任何需要它的脚本:

source log

如果可能的话,我想做的是将STDERR重定向到log error <message>,这样我就不必检查每个命令都会退出代码以查找错误。类似exec 2> log error之类的内容,以便捕获每条错误消息。

感谢任何帮助

感谢

1 个答案:

答案 0 :(得分:4)

设置trap 以下日志功能的定义:

# define a trap function
error_handler() {
    log error "I got an error on line:${1}, exit status of last command: ${2}"
    trap - ERR
}

# activate the trap
trap 'error_handler ${LINENO} $?' ERR

#### paste in the following your commands

编辑:trap - ERR删除陷阱,如果您打算多次使用陷阱(如果您的脚本在第一次错误后没有终止),只需对其进行评论。