Bash-日志记录功能-printf

时间:2020-08-30 20:27:29

标签: bash sh

我正在尝试为bash创建记录器。问题是直接打印正常,但是LOGGER_FUNC无法正确处理阵列。

当前,我可以打印应该记录的数据:

DEBUG_data_ARRAY=(hi ho no bugs here no)
printf "\n%s" "${DEBUG_data_ARRAY[@]}"
printf "\n%s %s" "${DEBUG_data_ARRAY[@]}"

在其中应将printf替换为:

LOGGER_FUNC "\n%s" "${DEBUG_data_ARRAY[@]}"
LOGGER_FUNC "\n%s %s" "${DEBUG_data_ARRAY[@]}"

记录器功能:

LOGGER_FUNC () {
    format=$1
    message=$2
    if [[ $VERBOSE == 0 ]]; then
        printf "${format[@]}" "${message[@]}"
    fi
    if [[ $VERBOSE == 1 ]]; then
         printf "${format[@]}" "${message[@]}" >> $DEBUG_FILE
    fi
    if [[ $VERBOSE == 2 ]]; then
        printf "${format[@]}" "${message[@]}"
        printf "${format[@]}" "${message[@]}" >> $DEBUG_FILE
    fi
}

预期结果如下:

hi 
ho 
no 
bugs
here 
no

hi ho 
no bugs
here no

2 个答案:

答案 0 :(得分:4)

format=$1
message=$2

这将创建两个标量变量。要使message成为包含$2$3$4等的数组,请输入:

format=$1
message=("${@:2}")

然后,由于format是标量,因此您可以只写$format而不是${format[@]}

if [[ $VERBOSE == 0 ]]; then
    printf "$format" "${message[@]}"
fi
if [[ $VERBOSE == 1 ]]; then
     printf "$format" "${message[@]}" >> "$DEBUG_FILE"
fi
if [[ $VERBOSE == 2 ]]; then
     printf "$format" "${message[@]}"
     printf "$format" "${message[@]}" >> "$DEBUG_FILE"
fi

答案 1 :(得分:1)

使用提供给函数的参数:

#!/usr/bin/env sh

LOGGER_FUNC() {
  # shellcheck disable=SC2059 # Variable format string
  printf "$@" | case $VERBOSE in
    1) cat ;;
    2) cat >>"$DEBUG_FILE" ;;
    3) tee -a "$DEBUG_FILE" ;;
  esac
}

或实现不需要内容参数的流记录器,而从stdin中获取它:

#!/usr/bin/env bash

# stream_logger
# Log stdin with options
# &1: Verbose level:
#     1: stdout only
#     2: debug file only
#     3: both stdout and debug file
# &2: Optional debug file path
stream_logger() {
  if [ $# -eq 0 ] || [ "$1" -eq 0 ]; then
    cat >/dev/null
  elif [ $# -eq 1 ] || [ "$1" -eq 1 ]; then
    cat
  elif [ $# -eq 2 ]; then
    if [ "$1" -eq 2 ]; then
      cat >>"$2"
    elif [ "$1" -eq 3 ]; then
      tee -a "$2"
    fi
  fi
}

DEBUG_data_ARRAY=(hi ho no bugs here no)

echo 'hello' | stream_logger # print nothing

# Output to stdout only
printf '\n%s' "${DEBUG_data_ARRAY[@]}" | stream_logger 1
printf '\n%s %s' "${DEBUG_data_ARRAY[@]}" | stream_logger 1

# Output to file1.log only
printf '\n%s' "${DEBUG_data_ARRAY[@]}" | stream_logger 2 file1.log
printf '\n%s %s' "${DEBUG_data_ARRAY[@]}" | stream_logger 2 file1.log

# Output to file2.log and stdout
printf '\n%s' "${DEBUG_data_ARRAY[@]}" | stream_logger 3 file2.log
printf '\n%s %s' "${DEBUG_data_ARRAY[@]}" | stream_logger 3 file2.log