Shell脚本从最近一小时的日志中获取异常

Imr*_*han 5 shell grep parsing solaris tail

我正在开发脚本,它将grep最近一小时的日志并检查任何异常并发送solaris平台的电子邮件.

我做了以下步骤

grep -n -h date +'%Y-%m-%d %H:%M' test.logs
Run Code Online (Sandbox Code Playgroud)

上面的命令给我行号,然后我做了以下

tail +6183313 test.log | grep 'exception'
Run Code Online (Sandbox Code Playgroud)

样本日志

2014-02-17 10:15:02,625 | WARN  | m://mEndpoint | oSccMod | 262 - com.sm.sp-client - 0.0.0.R2D03-SNAPSHOT | 1201 or 101 is returned as exception code from SP, but it is ignored
2014-02-17 10:15:02,625 | WARN  | m://mEndpoint | oSccMod | 262 - com.sm.sp-client - 0.0.0.R2D03-SNAPSHOT | SP error ignored and mock success returned
2014-02-17 10:15:02,626 | INFO  | 354466740-102951 | ServiceFulfill | 183 - org.apache.cxf | Outbound Message
Run Code Online (Sandbox Code Playgroud)

请建议任何更好的替代方案来执行上述任务.

Joh*_*024 9

使用GNU date,可以使用:

 grep "^$(date -d -1hour +'%Y-%m-%d %H')" test.logs | grep 'exception'| mail -s "exceptions in last hour of test.logs" ImranRazaKhan
Run Code Online (Sandbox Code Playgroud)

上面的第一步是从最后一小时选择所有日志条目.这是grep通过查找以一小时前匹配的年 - 月 - 日和小时开头的所有行来完成的:

grep "^$(date -d -1hour +'%Y-%m-%d %H')" test.logs
Run Code Online (Sandbox Code Playgroud)

管道中的下一步是从那些行中选择具有异常的行:

grep 'exception'
Run Code Online (Sandbox Code Playgroud)

管道中的最后一步是发送邮件:

mail -s "exceptions in last hour of test.logs" ImranRazaKhan
Run Code Online (Sandbox Code Playgroud)

以上内容将邮件发送给ImranRazaKhan(或您选择的任何电子邮件地址),主题为"test.logs的最后一小时的例外".

不应低估-d选项的便利性date.从当前小时中减去1似乎很简单,但是,如果当前小时是12点,那么我们需要调整日期和小时.如果当月的第一个小时是凌晨12点,我们还必须更改月份.同样是一年.当然,2月在闰年期间需要特别考虑.

使上述内容适应Solaris:

考虑三种情况:

  1. 在Solaris 11或更高版本下,可以使用GNU date实用程序/usr/gnu/bin/date.因此,我们只需要指定一个路径date:

     grep "^$(/usr/gnu/bin/date -d -1hour +'%Y-%m-%d %H')" test.logs | grep 'exception'| mail -s "exceptions in last hour of test.logs" ImranRazaKhan
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在Solaris 10或更早版本下,可以下载并安装GNU日期

  3. 如果GNU日期仍然不可用,我们需要找到另一种方法来查找一小时前的日期和时间.最简单的解决方法是选择一个比您的时区晚一个小时的时区.如果该时区是香港,则使用:

     grep "^$(TZ=HongKong date +'%Y-%m-%d %H')" test.logs | grep 'exception'| mail -s "exceptions in last hour of test.logs" ImranRazaKhan
    
    Run Code Online (Sandbox Code Playgroud)