博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
bash 获取时间段内的日志内容
阅读量:4509 次
发布时间:2019-06-08

本文共 2234 字,大约阅读时间需要 7 分钟。

需求,获取时段内的/var/log/messages文件内出现错误的消息,支持多行的消息,支持天,小时分钟,秒级的区间,可以修改监控的日志对象

 

#!/bin/bashif [ $# != 1 ] ; thenecho "USAGE: $0 num[Y|D|H|M|S]"echo " e.g.: $0 12h"exit 1;fi interval=$1unit=$(echo $interval | tr -d [:blank:] |tr -d [:digit:] |tr -t [a-z] [A-Z])val=$(echo $interval | tr -d [:blank:] |tr -d [:alpha:] )#echo $val#echo $unitcase $unit inY)      unit="years"	;;D)		unit="days" 	;;H)	unit="hours"	;;M)	unit="minutes"	;;S)		unit="seconds"	;;*)	echo "not"	exit 1;	;;esac#echo $unitts=$(date -d"-${val}${unit}" +"%s")echo $ts #date span one year 计算两年之间的秒数cts=$(date +"%s")x1=$(date -d"$(date +%Y)-01-01 00:00:00" +"%s") x2=$(date -d"$(date -d'-1years' +%Y)-01-01 00:00:00" +"%s")((secs=$x1-$x2))checkfile=/var/log/messages#checkfile=/home/student/test.txt#first_line=$(awk -v ts="$ts" '{"date -d \""$1" "$2" "$3"\" +%s 2>/dev/null"|getline dt; if(dt>ts) {print $0; exit;}}' $checkfile)first_line=$(awk -v secs="$secs" -v ts="$ts" -v cts="$cts" '{"date -d \""$1" "$2" "$3"\" +%s 2>/dev/null"|getline dt;if(dt>cts){dt=dt-secs;}if(dt>ts) {print $0; exit;}}' $checkfile)echo "firstline is $first_line"if [ "$first_line"X == "X" ]; then  exit 1; fibasedir=$(cd `dirname $0`;pwd)#echo "basedir is $basedir"log=$basedir/linux_messages.log>$log#function to handle one msghandleOneMsg(){msg="$1"has_error=$(echo "$msg"|grep -oie "\berror\b")if [ "$has_error"X != "X" ]; then#first we should encode the < > &msg_out=$(echo "$msg" |sed 's/&/&/g'| sed 's/
/\>/g' )cat <
>$log
`hostname`
LINUX
`date +"%Y-%m-%d %T"`
messages
$msg_out
EOFfi}OLDIFS=IFSIFS=$'\n'for line in $(grep -A100000 -F "$first_line" $checkfile)do#date ..... one message is start with date #before another msg is the last msg's bodyline_begin=$(echo $line | awk '{print $1,$2,$3}')#echo "line begin is $line_begin"line_begin_ts=$(date -d "$line_begin" "+%s" 2>/dev/null)#echo "line begin ts is $line_begin_ts"if [ "${line_begin_ts}"X == "X" -o "$msg"X == "X" ] ; then msg="${msg}"$'\n'"${line}" continue;#consume next linefi handleOneMsg "$msg" msg=$linedonehandleOneMsg "$msg"IFS=$OLDIFS

 

转载于:https://www.cnblogs.com/huaxiaoyao/p/7864922.html

你可能感兴趣的文章
Excel:一些方法的理解
查看>>
【转】在RHEL上升级Python
查看>>
java:环境变量设置
查看>>
Servlet的学习之Response响应对象(3)
查看>>
基础知识回顾——上下文管理器
查看>>
ARM(RISC)和x86(CISC)的技术差异
查看>>
第3章 对象基础
查看>>
文件压缩与解压缩
查看>>
android 搜索自动匹配关键字并且标红
查看>>
Android ViewPager使用详解
查看>>
python爬虫之scrapy的pipeline的使用
查看>>
mysql 1366错误
查看>>
mfc 导出数据保存成excel和txt格式
查看>>
让Android中的webview支持页面中的文件上传
查看>>
UML基础
查看>>
Oracle 从Dump 文件里提取 DDL 语句 方法说明
查看>>
实现winfrom进度条及进度信息提示
查看>>
关于Spring.Net的singleton和singlecall的讨论
查看>>
vue项目目录结构
查看>>
程序员自学路上的一些感悟
查看>>