Python日志:在添加新条目之前计算时间

2024-10-01 15:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编辑一个python脚本,用plex mediaserver的日志来控制家用电器(sonos、hue等)

到目前为止事情进展顺利,现在我正纠结于一个我找不到答案的问题。这是我迈出的第一步,请耐心等待

我有一个日志文件,它以以下格式收集会话信息:

...

2014-09-13 14:40:02 johnedoe is watching 30c3 Keynote

2014-09-13 14:48:06 thomas is watching Band of Brothers

2014-09-13 15:28:03 johnedoe is watching The Zero Theorem

...

如果检测到新会话,脚本将评估“johnedoe正在监视30c3注释记号”部分是否已存在。我想包括一个时间戳检查,它不仅检查会话是否存在,而且还检查已经记录的会话是否早于两个小时

In pseudocode: if (alert not in log) or (if alert in log and older than two hours):

我可以直接访问相应的时间戳吗,还是我必须要regex行?非常感谢您的帮助。非常感谢

这是代码的结尾:

logLocation = '/storage/downloads/plexMon.log'  
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=logLocation, level=logging.INFO)
log = open(logLocation).read()
server = urllib2.urlopen('http://127.0.0.1:32400/status/sessions') 
data = server.read()
server.close()
tree = ET.fromstring(data)
for video in tree.iter('Video'):
  show = video.get('grandparentTitle')
  episode = video.get('title')
  if show == "None":
    title = episode
  else:
    title = '%s - %s' % (show, episode)
    user = video.find('User').get('title').split('@')[0]
  alert = '%s is watching %s' % (user, title)
  if alert not in log:
    logging.info(alert)
    if all(i not in alert for i in ignoreAlertList):
      sendAlert(alert)
      if user == "johnedoe":
          b = Bridge('192.168.1.109') 
          b.set_light(1, 'bri', 50)
          my_zone = SoCo('192.168.1.105')
          my_zone.unjoin()
          my_zone.pause()

Tags: inloggetifservertitleislogging
1条回答
网友
1楼 · 发布于 2024-10-01 15:33:16

如果不使用正则表达式,这可能更容易实现,如果您使用:

log_lines = open(logLocation).readlines() # read log files as a list[] of lines

而不是:

log = open(logLocation).read()

然后使用类似于:

for line in log_lines:
    if(line.__contains__(alert)):
        partsOfLine = str(line).split()
        dateParts = str(partsOfLine[0]).split("-")
        timeParts = str(partsOfLine[1]).split(":")
        alerttime = datetime.datetime(int(dateParts[0]),int(dateParts[1]),int(dateParts[2]),int(timeParts[0]),int(timeParts[1]),int(timeParts[2]))
        timediff_in_min = (alerttime - datetime.now()).total_seconds()/60
        if(timediff_in_min >= 120):
            print "ignoring older than 2 hours"
        else:
            print "new alert in the last 2 hours"

相关问题 更多 >

    热门问题