这篇博客介绍一下Linux下面一个非常好用的日志打印的工具:logger,shell脚本中使用也非常多。
1、简介:
logger
是系统日志模块syslog
所提供的shell命令行接口,在CentOS上由系统自带的软件包util-linux-ng
所提供,可以将文件,或者自定义的字符串信息通过syslog的方式打印到预设的日志文件中,还可以设置日志级别,打印进程PID等。
2、用法:
2.1、语法:
logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]
2.2、命令行选项:
OPTIONS | DESCRIPTION |
---|---|
-i | 在系统日志中记录产生这条日志的进程的PID |
-s | 将消息记录到标准错误以及系统日志中 |
-f file | 将指定文件中的内容逐行记录到系统日志当中 |
-p pri | 输入具有指定优先级的消息。 优先级可以用数字表示,也可以是”facility.level”对。例如,“-p local3.info”将消息作为本地设备中的信息级别进行日志记录。 默认是“user.notice” |
-t tag | 使用指定的标记来标记日志中的每一行 |
-u sock | 写入指定的socket,而不是到内置syslog日志 |
message | 将消息写入日志;如果未指定,并且未提供-f标志,则会记录标准输入 |
返回状态码:
- 0 : 成功;
- > 0 : 产生错误.
有效的级别名称为:alert, crit, debug, emerg, err, error(已弃用的err的同义词), info, notice, panic(已弃用的emerg的同义词),warning, warn(已弃用的warning的同义词). 对于这些级别的优先级别和预期目的,请参阅syslog(3).
3、代码示例:
首先我们在rsyslog中定义一个本地的日志级别,防止测试或者正式使用过程中与系统日志记录到同一个文件中,导致查阅的时候不方便。
## /etc/rsyslog.conf 添加配置 ## local5.* /var/log/custom.log commandline > /etc/init.d/rsyslog restart
使用示例:
## 1、记录message信息 commandline > logger -p local5.notice -t custom -s "first message" custom: first message commandline > cat /var/log/custom.log Apr 26 23:36:57 leidy_201 custom: first message ## 2、记录PID信息: commandline > logger -p local5.warn -i -t custom "second message" commandline > tail -n1 /var/log/custom.log Apr 26 23:41:18 leidy_201 custom[1961]: second message ## 3、从文件中读取并记录到系统日志里面 commandline > cat install.log Installing grub-0.97-94.el6_7.1.x86_64 Installing efibootmgr-0.5.4-13.el6.x86_64 Installing sudo-1.8.6p3-24.el6.x86_64 commandline > logger -p local5.error -i -t install -f install.log commandline > cat /var/log/custom.log Apr 26 23:45:37 leidy_201 install[1967]: Installing grub-0.97-94.el6_7.1.x86_64 Apr 26 23:45:37 leidy_201 install[1967]: Installing efibootmgr-0.5.4-13.el6.x86_64 Apr 26 23:45:37 leidy_201 install[1967]: Installing sudo-1.8.6p3-24.el6.x86_64 ## 4、通过管道获取记录并记录到syslog中去 commandline > echo "from pipeline" | logger -p local5.info -i -t install [root@leidy_201 ~]# cat /var/log/custom.log Apr 26 23:48:09 leidy_201 install[1971]: from pipeline
暂无评论