Bash - 日志功能 - printf

Bash - logging function - printf

我正在尝试为 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=
    message=
    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
format=
message=

这将创建两个标量变量。要使 message 成为包含 </code>、<code></code> 等的数组,请写:</p> <pre><code>format= 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

使用提供给函数的参数:

#!/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 ] || [ "" -eq 0 ]; then
    cat >/dev/null
  elif [ $# -eq 1 ] || [ "" -eq 1 ]; then
    cat
  elif [ $# -eq 2 ]; then
    if [ "" -eq 2 ]; then
      cat >>""
    elif [ "" -eq 3 ]; then
      tee -a ""
    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