记录bash和stdout中的函数

时间:2010-08-19 18:26:09

标签: bash logging stdout

我希望能够将日志消息放在bash函数的中间,而不会影响这些函数的输出。例如,请考虑以下函数log()get_animals()

# print a log a message
log ()
{
    echo "Log message: $1"
}

get_animals()
{
    log "Fetching animals"
    echo "cat dog mouse"
}

values=`get_animals`
echo $values

之后$values包含字符串"Log message: Fetching animals cat dog mouse"

我应该如何修改此脚本,以便"Log message: Fetching animals"输出到终端,$values包含"cat dog mouse"

4 个答案:

答案 0 :(得分:12)

您可以使用>& 2

将输出重定向到文件句柄2上的sdterr错误文件

示例:

# print a log a message
log ()
{
echo "Log message: $1" >&2
}

get_animals()
{
log "Fetching animals"
echo "cat dog mouse"
}

values=`get_animals`
echo $values

``只接受stdout上的输出,而不是stderr上的输出。另一方面,控制台显示两者。

如果您真的想要stdout上的日志消息,您可以在分配给变量后将错误重定向回到stdout:

# print a log a message
log ()
{
    echo "Log message: $1" >&2
}

get_animals()
{
    log "Fetching animals"
    echo "cat dog mouse"
}

values=`get_animals` 2>&1
echo $values

答案 1 :(得分:10)

choroba's solution to another question显示了如何使用exec打开新的文件描述符。

将该解决方案翻译成这个问题的方法如下:

# Open a new file descriptor that redirects to stdout:
exec 3>&1

log ()
{
    echo "Log message: $1" 1>&3
}

get_animals()
{
    log "Fetching animals"
    echo "cat dog mouse"
}

animals=`get_animals`
echo Animals: $animals

执行上述产生:

Log message: Fetching animals
Animals: cat dog mouse

有关在Bash中使用I / O重定向和文件描述符的更多信息,请访问:

答案 2 :(得分:4)

    #
    #------------------------------------------------------------------------------
    # echo pass params and print them to a log file and terminal
    # with timestamp and $host_name and $0 PID
    # usage:
    # doLog "INFO some info message"
    # doLog "DEBUG some debug message"
    # doLog "WARN some warning message"
    # doLog "ERROR some really ERROR message"
    # doLog "FATAL some really fatal message"
    #------------------------------------------------------------------------------
    doLog(){
        type_of_msg=$(echo $*|cut -d" " -f1)
        msg=$(echo "$*"|cut -d" " -f2-)
        [[ $type_of_msg == DEBUG ]] && [[ $do_print_debug_msgs -ne 1 ]] && return
        [[ $type_of_msg == INFO ]] && type_of_msg="INFO " # one space for aligning
        [[ $type_of_msg == WARN ]] && type_of_msg="WARN " # as well

        # print to the terminal if we have one
        test -t 1 && echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S %Z"` [$run_unit][@$host_name] [$$] ""$msg"

        # define default log file none specified in cnf file
        test -z $log_file && \
            mkdir -p $product_instance_dir/dat/log/bash && \
                log_file="$product_instance_dir/dat/log/bash/$run_unit.`date "+%Y%m"`.log"
        echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S %Z"` [$run_unit][@$host_name] [$$] ""$msg" >> $log_file
    }
    #eof func doLog

答案 3 :(得分:1)

您可以将日志输出重定向到标准错误流:

log()
{
    echo 1>&2 "Log message: $1"
}