]> git.treefish.org Git - logalert.git/blob - src/misc.py
added log level option
[logalert.git] / src / misc.py
1 import logging
2 import os
3 import shlex
4 import subprocess
5 import time
6
7 def follow_file(path):
8     while True:
9         try:
10             fd = os.open(path, os.O_RDONLY)
11             current_ino = os.fstat(fd).st_ino
12             with os.fdopen(fd, "r") as f:
13                 logging.info("Re-attached to file.")
14                 for line in f: pass
15                 while True:
16                     line = f.readline()
17                     if not line:
18                         if os.stat(path).st_ino != current_ino or \
19                            os.stat(path).st_size < f.tell():
20                             break
21                         else:
22                             time.sleep(1.0)
23                             yield None
24                     else:
25                         yield line.rstrip("\n")
26         except FileNotFoundError:
27             time.sleep(1.0)
28             yield None
29
30 def feed_handler(cmd, data):
31     try:
32         handler = subprocess.Popen(shlex.split(cmd),
33                                    stdin=subprocess.PIPE,
34                                    stdout=subprocess.PIPE,
35                                    stderr=subprocess.PIPE,
36                                    encoding='UTF-8')
37         out_data, err_data = handler.communicate("%s\n" % data)
38         if handler.returncode != 0:
39             logging.warning("Handler exited with non-zero return code %d! (%s)" %
40                             (handler.returncode, err_data))
41     except Exception as e:
42         logging.error("Error feeding handler: %s" % str(e))
43
44 def create_msg(title, icon, logfile, text, lines):
45     msg = "<b>%s</b> <i>%s</i> %s" % (title, logfile, icon)
46     msg += "<br>%s" % text
47     msg += "<br><pre>"
48     for line in lines: msg += line + "\n"
49     msg += "</pre>"
50     return msg