Bash-로깅 기능-printf
Aug 30 2020
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
답변
4 JohnKugelman Aug 30 2020 at 20:35
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 LéaGris Aug 30 2020 at 21:08
함수에 제공된 인수 사용 :
#!/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