1、概述
自定义日志记录函数LOG,打印日志时附加日期时间、打印日志的文件名、输出日志等级等信息。
2、源码实现
# 自定义日志函数
# 用法: LOG 日志等级 日志内容
# 日志等级:INFO,WARN,ERROR,DEBUG
# 用法举例:LOG INFO "this is the test" # LOG "this is test" : 没有写日志等级,那么缺省设置日志等级为 INFO
LOG()
{
LOG_DIR="/opt/log"
LOG_FILE="${LOG_DIR}/my.log"
local log_level=$1
local log_content=$2
#如果日志等级不是INFO,WARN,ERROR,DEBUG,直接把缺省登记设置为INFO,把带的第一个参数当着日志内容,丢弃第二个参数
if [ "${log_level}" != "INFO" -a "${log_level}" != "WARN" -a "${log_level}" != "ERROR" -a "${log_level}" != "DEBUG" ]; then
log_level="INFO"
log_content=$1
fi
if [ -z "${log_content}" ]; then
return
fi
local curtime=`date +"%Y-%m-%d %H:%M:%S"`
local script_name=$(basename $0) #如果不在文件中使用,直接在命令行使用, 则script_name为空,不显示该参数
mkdir -p ${LOG_DIR}
echo "${curtime} ${script_name} ${log_level} ${log_content}" >> ${LOG_FILE} 2>&1
}
3、日志运行效果
前半部是在test.sh文件中使用LOG INFO hello等模式,调用LOG,日志会显示年月日时间,打印日志的文件,日志等级和具体日志内容。
[root@others ~]# tailf /opt/log/my.log
2023-06-15 14:54:58 INFO hello
2023-06-15 15:00:34 test.sh INFO hello
2023-06-15 15:02:09 test.sh DEBUG this is the debug information .
2023-06-19 11:27:19 test.sh DEBUG this is the debug information .
2023-06-25 16:35:08 INFO hahaha
2023-06-25 16:35:19 ERROR 123
2023-06-25 16:36:22 DEBUG 1234565
2023-06-25 16:37:26 INFO 1
4、日志使用的其它说明
4.1、设定缺省日志等级
如果日志等级不是INFO,WARN,ERROR,DEBUG,直接把缺省等级设置为INFO,把带的第一个参数当着日志内容,丢弃第二个参数
如:LOG hahaha 123456 ,会把123456丢弃,记录为如下:
2023-06-25 16:39:50 INFO hahaha
4.2、 显示调用该功能的文件
使用文件调用函数,会显示打印该日志的文件名,如上图为test.sh ,
如果直接用命令行调用LOG,则不显示调用LOG的文件名,会有一个warning:
basename: invalid option -- 'b'
4.3、其它
如果需要输入的日志有空格,需要用" " 把内容引起来。
LOG "this is a test"
如果日志没有空格,可以不用引号
LOG hahahahaha