记录bash和stdout中的函数

Ada*_*dam 13 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
Run Code Online (Sandbox Code Playgroud)

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

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

Pet*_*ans 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
Run Code Online (Sandbox Code Playgroud)

``只在stdout上输出,而不是在stderr上.另一方面,控制台同时显示两者.

如果你真的想要stdout上的Log消息,你可以在分配给变量后将错误重定向回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
Run Code Online (Sandbox Code Playgroud)


Dav*_*son 12

choroba对另一个问题的解决方案显示了如何使用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
Run Code Online (Sandbox Code Playgroud)

执行上述产生:

Log message: Fetching animals
Animals: cat dog mouse
Run Code Online (Sandbox Code Playgroud)

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

  • 为什么这个解决方案不是公认的解决方案 它解决了OP提出的确切问题. (2认同)

Yor*_*iev 5

    #
    #------------------------------------------------------------------------------
    # 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
Run Code Online (Sandbox Code Playgroud)