代码世界Shell语言用例

bash的一个简易log模型

2017-12-15  本文已影响1人  CodingCode

bash的一个log模型,打印log产生的时间,所在文件,函数,以及行号。

定义log函数

$ cat log.sh 
#!/bin/bash

# LOG {LEVEL} {MESSAGE}
function LOG() {
    typeset filename=$(basename ${BASH_SOURCE[2]})
    typeset lineno=${BASH_LINENO[1]}
    typeset funcname=${FUNCNAME[2]}
    typeset loglevel=${1}
    shift 1
    printf "$(date +'%Y-%m-%d %H:%M:%S') [${filename}:${funcname}:${lineno}] ${loglevel}: ${*}\n"
}

function TRACE() {
    LOG "TRACE" "${*}"
}

function DEBUG() {
    LOG "DEBUG" "${*}"
}

function INFO() {
    LOG "INFO " "${*}"
}


function WARN() {
    LOG "WARN " "${*}"
}

function ERROR() {
    LOG "ERROR" "${*}"
}

#declare -fx LOG
#declare -fx TRACE
#declare -fx DEBUG
#declare -fx INFO
#declare -fx WARN
#declare -fx ERROR

使用

$ cat -n b.sh 
     1  #!/bin/bash
     2
     3  # import log.sh
     4  source log.sh
     5
     6  TRACE "aaa"
     7  DEBUG "bbb"
     8  INFO  "ccc"
     9  WARN  "ddd"
    10  ERROR "eee"
    11
    12  function foo() {
    13      INFO "foo"
    14  }
    15
    16  foo
    17
    18  INFO # empty line
    19  INFO THANK YOU
    20

运行结果

$ ./b.sh 
2017-12-15 23:36:18 [b.sh:main:6] TRACE: aaa
2017-12-15 23:36:18 [b.sh:main:7] DEBUG: bbb
2017-12-15 23:36:18 [b.sh:main:8] INFO : ccc
2017-12-15 23:36:18 [b.sh:main:9] WARN : ddd
2017-12-15 23:36:18 [b.sh:main:10] ERROR: eee
2017-12-15 23:36:18 [b.sh:foo:13] INFO : foo
2017-12-15 23:36:18 [b.sh:main:18] INFO : 
2017-12-15 23:36:18 [b.sh:main:19] INFO : THANK YOU

层级调用

目前我也不知道怎么处理,所以只能在每一个脚本里面都引用log.sh,例如脚本a.sh调用脚本b.sh,我们需要在a.sh和b.sh里面同时引用log.sh

$ cat a.sh 
#!/bin/bash

# import log.sh
source log.sh

TRACE "AAA"
DEBUG "BBB"
INFO  "CCC"
WARN  "DDD"
ERROR "EEE"

./b.sh

INFO BYE

运行结果

$ ./a.sh 
2017-12-15 23:39:06 [a.sh:main:6] TRACE: AAA
2017-12-15 23:39:06 [a.sh:main:7] DEBUG: BBB
2017-12-15 23:39:06 [a.sh:main:8] INFO : CCC
2017-12-15 23:39:06 [a.sh:main:9] WARN : DDD
2017-12-15 23:39:06 [a.sh:main:10] ERROR: EEE
2017-12-15 23:39:06 [b.sh:main:6] TRACE: aaa
2017-12-15 23:39:06 [b.sh:main:7] DEBUG: bbb
2017-12-15 23:39:06 [b.sh:main:8] INFO : ccc
2017-12-15 23:39:06 [b.sh:main:9] WARN : ddd
2017-12-15 23:39:06 [b.sh:main:10] ERROR: eee
2017-12-15 23:39:06 [b.sh:foo:13] INFO : foo
2017-12-15 23:39:06 [b.sh:main:18] INFO : 
2017-12-15 23:39:06 [b.sh:main:19] INFO : THANK YOU
2017-12-15 23:39:06 [a.sh:main:14] INFO : BYE
上一篇 下一篇

猜你喜欢

热点阅读