从过去一小时的日志中获取异常的Shell脚本



我正在开发脚本,该脚本将grep过去一个小时的日志,检查任何异常并为solaris平台发送电子邮件。

我做了以下步骤

grep -n -h date +'%Y-%m-%d %H:%M' test.logs

上面的命令给了我行号,然后我按照

tail +6183313 test.log | grep 'exception'

样本日志

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

请提出任何更好的替代方案来执行上述任务。

使用GNUdate,可以使用:

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

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

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

管道中的下一步是从这些线路中选择有例外的线路:

grep 'exception'

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

mail -s "exceptions in last hour of test.logs" ImranRazaKhan

以上邮件发送给ImranRazaKhan(或您选择的任何电子邮件地址),主题行为"测试最后一小时的异常。日志"。

不应低估将-d选项设置为date的便利性。从当前小时减去1似乎很简单,但如果当前小时是凌晨12点,那么我们需要调整当天和小时。如果时间是本月1日上午12点,我们也必须更改月份。今年也是如此。当然,二月在闰年需要特别考虑。

将以上内容适配到Solaris:

考虑三种情况:

  1. 在Solaris 11或更高版本下,GNUdate实用程序可在/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
    
  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
    

您可以这样做:

dt="$(date -d '1 hour ago' "+%m/%d/%Y %H:%M:%S")"
awk -v dt="$dt" '$0 ~ dt && /exceltion/' test.logs

扫描数百万行日志听起来效率非常低。我建议更改应用程序的log4j(看起来像什么)配置,以便每小时剪切一个新的日志文件。这样,跟踪最近的文件就变得轻而易举了。

最新更新