tail 和 grep 日志和邮件 (linux)

问题描述 投票:0回答:4

我想用 grep 跟踪日志文件并通过邮件发送 喜欢:

tail -f /var/log/foo.log | grep error | mail -s subject [email protected]

我该怎么做?

email shell grep tail
4个回答
23
投票

您想在发送电子邮件发生错误时发送电子邮件吗?这可能会失败;)

但是你可以尝试这样的事情:

tail -f $log |
grep --line-buffered error |
while read line
do
    echo "$line" | mail -s subject "$email"
done

对于 grep 输出中的每一行都会发送一封电子邮件。

使用

运行上面的 shell 脚本
nohup ./monitor.sh &

所以它将继续在后台运行。


2
投票

我会尝试一下。如果我讨厌的 bash 代码得到仔细检查,也许我会学到一些东西。有可能已经有无数的解决方案可以做到这一点,但我不会找出答案,因为我确信您已经拖网了网络海洋的深度和宽度。听起来你想要的可以分为两部分:1)定期获取文件的“最新尾部”,2)如果最新尾部确实存在,则通过电子邮件发送。对于 1) 中的定期间隔,请使用 cron。为了获得 2) 中的最新尾部,您必须跟踪文件大小。下面的 bash 脚本就是这样做的 - 它是 2) 的解决方案,可以由 cron 调用。它使用缓存的文件大小来计算需要邮寄的文件块。请注意,对于文件 myfile,会创建另一个文件 .offset.myfile。此外,该脚本不允许在文件名中包含路径部分。重写或在调用中修复它[例如(cd /foo/bar && segtail.sh zut),假设它被称为 segtail.sh ].

#!/usr/local/bin/bash
file=$1
size=0
offset=0
if [[ $file =~ / ]]; then
   echo "$0 does not accept path components in the file name" 2>&1
   exit 1
fi
if [[ -e .offset.$file ]]; then
   offset=$(<".offset.$file")
   fi
if [[ -e $file ]]; then
   size=$(stat -c "%s" "$file")    # this assumes GNU stat, possibly present as gstat. CHECK!
                                   # (gstat can also be Ganglias Status tool - careful).
fi
if (( $size < $offset )); then     # file might have been reduced in size
   echo "reset offset to zero" 2>&1
   offset=0
fi
echo $size > ".offset.$file"
if [[ -e $file &&  $size -gt $offset ]]; then
   tail -c +$(($offset+1)) "$file" | head -c $(($size - $offset)) | mail -s "tail $file" foo@bar
fi

0
投票

怎么样:

mail -s“catalina.out 错误”[电子邮件受保护] < grep ERROR catalina.out


0
投票

我在每 60 分钟运行一次的 cronjob 中使用 1-liner,检查文件在过去 60 分钟内是否已更改。如果是这样,日志文件的最后 3 行将发送给我。

log_file=$(find /var/log/mylog.log -mmin -60) && [[ -n "$log_file" ]] && tail -n 3 "$log_file" | mail -s "Alert mylog" [email protected]
© www.soinside.com 2019 - 2024. All rights reserved.