2016年2月17日 星期三

[Linux 文章收集] Shell scripting: Write message to a syslog / log file

Source From Here 
Introduction 
syslog is the protocol as well as application to send message to Linux system logfile located at /var/log directory. Sysklogd provides two system utilities which provide support for system logging and kernel message trapping. Usually most program and apps use C or syslog application / library sending syslog messages. But how do you send message from a shell prompt or shell script? 

logger command 
Use logger command which is a shell command interface to the syslog system log module. It makes or writes one line entries in the system log file from the command line. Log message 'System rebooted for hard disk upgrade': 
# logger System rebooted for hard disk upgrade
# tail -f /var/log/messages
...
Feb 17 05:11:59 localhost root: System rebooted for hard disk upgrade

You can use logger command from a shell script. Consider following example: 
  1. #!/bin/bash  
  2. HDBS="db1 db2 db3 db4"  
  3. BAK="/sout/email"  
  4. [ ! -d $BAK ] && mkdir -p $BAK || :  
  5. /bin/rm $BAK/*  
  6. NOW=$(date +"%d-%m-%Y")  
  7. ATTCH="/sout/backup.$NOW.tgz"  
  8. [ -f $ATTCH ] && /bin/rm $ATTCH  || :  
  9. MTO="you@yourdomain.com"  
  10. for db in $HDBS  
  11. do  
  12. FILE="$BAK/$db.$NOW-$(date +"%T").gz"  
  13. mysqldump -u admin -p'password' $db | gzip -9 > $FILE  
  14. done  
  15. tar -jcvf $ATTCH $BAK  
  16. mutt -s "DB $NOW" -a $ATTCH $MTO <
  17. DBS $(date)  
  18. EOF  
  19. "$?" != "0" ] &&  logger "$0 - MySQL Backup failed" || :  
Last line will log a message in /var/log/messages file if backup failed. 

Other usage 
To log a message contained in the /var/log/myapp.log file, use: 
// -f, --file : log the contents of this file
# logger -f /var/log/myapp.log

Log the message to standard error (screen), as well as the system log: 
// -s, --stderr: output message to standard error as well
# logger -s "Hard disk full"

Maker your log with tag: 
// -t, --tag : mark every line with this tag
# logger -t 'john' hello mary
# tail /var/log/messages
...
Feb 17 05:24:02 localhost john: hello mary

Refer to the man page for more options: 
# man logger
# man syslogd


Supplement 
Tsung's Blog - Linux 如何將資料寫到 Syslog 
鳥哥 Linux 基礎文件 - 第十八章、認識與分析登錄檔

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...