如何从BASH中的日志文件中准确地获取过去一小时的日志? [英] How to accurately grab logs in the past hour from a log file in BASH?

查看:148
本文介绍了如何从BASH中的日志文件中准确地获取过去一小时的日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个cron作业的日志文件,其中的条目格式为

I have a log file for cron jobs with entries using the format of

Mar  8 17:30:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)

我希望能够定期检查日志,以查看是否运行了特定的CRON作业(每小时运行一次).通过grep可以轻松找到我想要的日志.

I want to be able to periodically checks the logs to see if a specific CRON job ( that runs hoursly) ran. Finding the logs I want have been easy via grep.

grep name_of_job logfile

但是我不确定如何准确地仅从过去一小时中获取日志,以查看是否有任何cron作业已运行.

But I'm unsure of how to accurately grab only the logs from the past hour to see if any cron jobs have ran.

我根据这篇文章尝试使用 awk 命令抢过最后一个小时我遇到了 awk 问题,因为我的日期戳分为多个字段.

I tried using the awk command to grab the last hour based on this post but I've had issues with awk because my datestamp is separated into multiple fields.

推荐答案

将您的问题写错了,我已经创建了虚拟日志,还请注意,时间到了我的时区.我还显示了运行脚本之前的当前时间.

wrt your problem I have created dummy logs, also note that time is wrt to my timezone. I have also displayed the current time before running the script.

$ cat file2
Mar  9 05:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar  9 04:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar  9 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar  5 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar  9 04:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
$ date
Wed Mar  9 05:40:10 IST 2016
$ ./script.bash 
Mar  9 05:20:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
Mar  9 05:35:01 hostname CROND[PROC_#]: (user) CMD (/path/to/job/)
$

script.bash的内容如下:

#!/bin/bash

while read -r line || [[ -n "$line" ]]
do
    log_date_str="$(awk '{print $1" "$2" "$3}' <<< "$line")"
    log_date="$(date -d "$log_date_str" +%s)"
    [[ $(($(date +%s)-$log_date)) -le 3600 ]] && echo "$line"
done < "file2"

我们从日志文件中获取日期,并将其转换为自 Unix时代,并从命令date +%s获取当前日期时间的相同格式.注意+%s是此处的格式. date -d dateString +%s可用于将字符串作为日期解析为所需的格式.

we get the date from the log file and convert it into number of seconds elapsed since Unix Epoch and also get that same format for current datetime from command date +%s Note +%s is the format here. date -d dateString +%s can be used to parse a string as date into a desired format.

一旦我们拥有了两个日期,我们就将其减去,然后找出差异小于3600秒(1小时)的那些结果;然后我们只打印出日志行.

Once we have both the dates we just subtract it and then find out those results which have difference less than 3600 seconds(1 hour); and then we just print out the log line.

您可以传递grep

这篇关于如何从BASH中的日志文件中准确地获取过去一小时的日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆