日志文件的Python-tail-f
我用下面的代码片段实现了python tail-f,该代码片段工作得非常好,因为我的程序通过python myprogram.py&日志文件的Python-tail-f,python,linux,tail,logfile,Python,Linux,Tail,Logfile,我用下面的代码片段实现了python tail-f,该代码片段工作得非常好,因为我的程序通过python myprogram.py& def follow(thefile): thefile.seek(0,2) while True: line = thefile.readline() if not line: time.sleep(0.1) continue yield line
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
传递给上述函数的文件是一个日志文件,它是从main传递的
# follow.py
# Follow a file like tail -f.
import smtplib
import time
import re
import logging
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from job import Job
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
def sendMail(job,occurtime):
COMMASPACE = ', '
outer = MIMEMultipart()
# msg = MIMEMultipart('alternative')
outer['Subject'] = 'ETL Failed for job:' + job
outer['From'] = 'eltmonitor@fms.com'
me= 'eltmonitor@ncellfms.com'
family = ["bibesh.pokhrel@huawei.com"]
outer['To'] = COMMASPACE.join(family)
inner = MIMEMultipart('alternative')
html = """\
<html>
<head></head>
<body>
<p>Dears,<br>
Please take necessary action to troubleshoot the ETL Error for job:""" + job + " at " + occurtime + """
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
inner.attach(part2)
outer.attach(inner)
# Connect to SMTP server and send the email
# Parameter are from=me, to=family and outer object as string for message body
try:
s = smtplib.SMTP('localhost')
s.sendmail(me,family,outer.as_string())
s.quit()
except SMTPException:
logging.info('Unable to send email')
if __name__ == '__main__':
while True:
logging.basicConfig(filename='/opt/etlmonitor/monitor.log',format='%(asctime)s %(levelname)s %(message)s',level=logging.DEBUG, filemode='w')
# Define two ETL Job object to store the state of email sent as boolean flag
fm =Job()
ncell =Job()
try:
with open("/opt/report/logs/GraphLog.log","r") as logfile:
# Continually read the log files line by line
loglines = follow(logfile)
# Do something with the line
for line in loglines:
# Extract the last word in the line of log file
# We are particulary looking for SUCCESS or FAILED word
# Warning!! leading whitespace character is also matched
etlmsg= re.search(".*(\s(\w+)$)",line)
if etlmsg:
# Remove leading whitespace
foundmsg = etlmsg.group(1).lstrip()
# Process on the basis of last word
# If it is SUCCESS , set the job mailsent flag to False so that no email is sent
# If it is FAILED and mailsent flag of job is False, send a email and set mailsent flag to True
# If it is FAILED and mailsent flag of job is True, do nothing as email was already sent
if foundmsg=='SUCCESS':
jobname= re.search(": Graph '(.+?)\'",line)
if jobname:
foundjob= jobname.group(1)
if foundjob =='Mirror.kjb':
logging.info('Ncell Mirror job detected SUCCESS')
ncell.p == False
elif foundjob =='FM_job.kjb':
fm.p == False
logging.info('Ncell Report job detected SUCCESS')
else:
logging.info('No job name defined for success message')
elif foundmsg =='FAILED':
jobname= re.search(": Graph '(.+?)\'",line)
timevalue=re.search("(.+?)\,",line)
if jobname and timevalue:
foundjob= jobname.group(1)
foundtime = timevalue.group(1)
if foundjob =='Mirror.kjb':
if ncell.p == True:
logging.info('Notification Email has been already sent for job: ' + foundjob)
elif ncell.p == False :
ncell.p = True
sendMail(foundjob,foundtime)
else:
logging.info("state not defined")
elif foundjob =="FM_job.kjb":
if fm.p == True:
logging.info('Notification Email has been already sent for job: ' + foundjob)
elif fm.p == False:
fm.p = True
sendMail(foundjob,foundtime)
else:
logging.info('Unkown state of job')
else:
logging.info('New job name found')
except IOError:
logging.info('Log file could not be found or opened')
#follow.py
#遵循像tail-f这样的文件。
导入smtplib
导入时间
进口稀土
导入日志记录
#以下是我们需要的电子邮件包模块
从email.mime.image导入MIMEImage
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
从作业导入作业
def跟踪(文件):
文件查找(0,2)
尽管如此:
line=file.readline()
如果不是直线:
睡眠时间(0.1)
持续
生产线
def sendMail(作业、发生时间):
逗号空间=','
外部=MIMEMultipart()
#msg=MIMEMultipart('alternative')
外部['Subject']=“作业的ETL失败:'+作业
外部['From']='eltmonitor@fms.com'
我eltmonitor@ncellfms.com'
家庭=[“bibesh。pokhrel@huawei.com"]
外部['To']=COMMASPACE.join(族)
内部=MIMEMultipart('alternative')
html=”“”\
亲爱的,
请采取必要的操作对作业“+job+”在“+occurtime+”处的ETL错误进行故障排除
"""
#记录这两部分的MIME类型-text/plain和text/html。
part2=MIMEText(html,'html')
#将部件附加到消息容器中。
#根据RFC 2046,在本例中,多部分消息的最后一部分
#HTML消息是最好的首选。
内部连接(第2部分)
外部。连接(内部)
#连接到SMTP服务器并发送电子邮件
#参数是from=me、to=family和作为消息体字符串的外部对象
尝试:
s=smtplib.SMTP('localhost')
s、 sendmail(我、家人、外部.as_string())
s、 退出
除SMTPException外:
logging.info('无法发送电子邮件')
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
尽管如此:
logging.basicConfig(文件名='/opt/etlmonitor/monitor.log',格式='%(asctime)s%(levelname)s%(message)s',level=logging.DEBUG,filemode='w')
#定义两个ETL作业对象,将发送的电子邮件状态存储为布尔标志
fm=作业()
ncell=Job()
尝试:
打开(“/opt/report/logs/GraphLog.log”,“r”)作为日志文件:
#连续逐行读取日志文件
日志行=跟随(日志文件)
#用绳子做点什么
对于日志行中的行:
#提取日志文件行中的最后一个字
#我们尤其在寻找成功或失败的字眼
#警告!!前导空格字符也匹配
etlmsg=re.search(“.*(\s(\w+$)”,第行)
如有必要,请发送邮件:
#删除前导空格
foundmsg=etlmsg.group(1).lstrip()
#基于最后一句话的过程
#如果成功,请将job mailsent标志设置为False,以便不发送电子邮件
#如果失败且作业的mailsent标志为False,则发送电子邮件并将mailsent标志设置为True
#若失败且作业的mailsent标志为True,则不执行任何操作,因为电子邮件已发送
如果foundmsg==“成功”:
jobname=re.search(“:Graph'(.+?)\”,第行)
如果作业名为:
foundjob=jobname.group(1)
如果foundjob=='Mirror.kjb':
logging.info('Ncell镜像作业检测到成功')
ncell.p==False
elif foundjob==“FM_job.kjb”:
fm.p==False
logging.info('Ncell报告作业检测到成功')
其他:
logging.info('没有为成功消息定义作业名称')
elif foundmsg==“失败”:
jobname=re.search(“:Graph'(.+?)\”,第行)
时间值=重新搜索(“(.+?)\,”行)
如果作业名称和时间值为:
foundjob=jobname.group(1)
foundtime=timevalue.group(1)
如果foundjob=='Mirror.kjb':
如果ncell.p==True:
logging.info('已为作业发送通知电子邮件:'+foundjob)
elif ncell.p==假:
ncell.p=真
sendMail(foundjob、foundtime)
其他:
logging.info(“未定义状态”)
elif foundjob==“FM_job.kjb”:
如果fm.p==真:
logging.info('已为作业发送通知电子邮件:'+foundjob)
elif fm.p==假:
fm.p=真
sendMail(foundjob、foundtime)
其他:
logging.info('作业的未知状态')
其他:
logging.info('找到新作业名称')
除IOError外:
logging.info('无法找到或打开日志文件')
我实际上是在用正则表达式读取行中的最后一个单词,并根据收到的最后一个单词执行一些任务
问题在于,日志文件(GraphLog.log)是根据文件大小滚入的。当这种情况发生时,我的程序