10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bashのちょっと便利なlogger

Posted at

log4shまで使うのはちょっと大げさだけど

  • 時刻、
  • ログレベル
  • ログレベルによる出力ファイル分割

程度のロギングの機能が欲しい時に使ってる。

common_logger.sh

# !/bin/bash

declare -r fd0_parent=$( LANG=C stat -Lc %d_%F_%i /proc/self/fd/0 )
log_impl_ () {

  [ "${LOG_INS}" = "" ] && return 0

  local dt=`date +'%Y-%m-%d %H:%M:%S'`
  local lvl=$1
  shift

  # 自分の入力ファイルを調べる
  local fd0=$( LANG=C stat -Lc %d_%F_%i /proc/self/fd/0 )

  #残りの引数をすべてログとして扱う
  local mes=""
  if [ $# -ne 0 ]; then
    mes="$* "
  fi

  local logfile=${LOG_INS}
  # 呼び出し元と自分の入力ファイルが同じなら引数のMSGだけを表示
  if [ "$fd0_parent" == "$fd0" ]; then
    printf "$dt %-5s $mes\n" [$lvl] >> ${logfile}
  else
    #  パイプの内容を出力
    local line
    IFS=''                  # read に先頭/末尾の空白も読ませる
    while read line; do
      if [ "$line" != "" ]; then
        printf "$dt %-5s $line\n" [$lvl] >> ${logfile}
      fi
    done
  fi
  return 0
}


# LOG処理定義 log levelを増やしたい場合は追加で記述
# echoの部分はわかりやすいから書いてるだけで消しても問題ない。
log() {       echo "$@" ; export LOG_INS=${COMMON_LOG:-"/var/log/log.log"} ; log_impl_ "INFO" "$@"; }
log_info () { echo "$@" ; export LOG_INS=${COMMON_LOG:-"/var/log/log.log"} ; log_impl_ "INFO" "$@"; }
log_debug() { echo "$@" ; export LOG_INS=${COMMON_LOG:-"/var/log/log.log"} ; log_impl_ "DEBUG" "$@"; }
log_err() {   echo "$@" ; export LOG_INS=${ERR_LOG:-"/var/log/err.log"}    ; log_impl_ "ERROR" "$@"; }

呼び出し

こんな感じに使う
log-test.sh

# !/bin/bash
. "./common_logger.sh"

log "info log."
log_debug "debug log."
echo "pipe log" | log
log_err "error log."

出力

/var/log/log.log

2014-05-13 17:33:25 [INFO] info log.
2014-05-13 17:33:25 [DEBUG] debug log.
2014-05-13 17:33:25 [INFO] pipe log

/var/log/err.log

2014-05-13 17:33:25 [ERROR] error log.
10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?