]> git.treefish.org Git - logalert.git/commitdiff
refactoring
authorAlexander Schmidt <alex@treefish.org>
Tue, 6 Oct 2020 19:27:30 +0000 (21:27 +0200)
committerAlexander Schmidt <alex@treefish.org>
Tue, 6 Oct 2020 19:27:30 +0000 (21:27 +0200)
src/logalert.py
src/misc.py [new file with mode: 0644]

index df9de076eb4e701577f7af5ebc83711ce6c8be2c..e2f02ccbd40f53c8a763f6d2435778374f9566f0 100755 (executable)
@@ -2,59 +2,13 @@
 
 import argparse
 import logging
-import os
-import shlex
-import subprocess
 import time
 
+import misc
+
 MAX_LINES = 10
 ALERT_INTERVAL = 86400
 
-def follow(path):
-    while True:
-        try:
-            fd = os.open(path, os.O_RDONLY)
-            current_ino = os.fstat(fd).st_ino
-            with os.fdopen(fd, "r") as f:
-                logging.info("Re-attached to log file.")
-                for line in f: pass
-                while True:
-                    line = f.readline()
-                    if not line:
-                        if os.stat(path).st_ino != current_ino or \
-                           os.stat(path).st_size < f.tell():
-                            break
-                        else:
-                            time.sleep(1.0)
-                            yield None
-                    else:
-                        yield line.rstrip("\n")
-        except FileNotFoundError:
-            time.sleep(1.0)
-            yield None
-
-def feed_handler(data):
-    try:
-        handler = subprocess.Popen(shlex.split(args.handler),
-                                   stdin=subprocess.PIPE,
-                                   stdout=subprocess.PIPE,
-                                   stderr=subprocess.PIPE,
-                                   encoding='UTF-8')
-        out_data, err_data = handler.communicate("%s\n" % data)
-        if handler.returncode != 0:
-            logging.warning("Handler exited with non-zero return code %d! (%s)" %
-                            (handler.returncode, err_data))
-    except Exception as e:
-        logging.error("Error feeding handler: %s" % str(e))
-
-def create_msg(title, icon, logfile, text, lines):
-    msg = "<b>%s</b> <i>%s</i> %s" % (title, logfile, icon)
-    msg += "<br>%s" % text
-    msg += "<br><pre>"
-    for line in lines: msg += line + "\n"
-    msg += "</pre>"
-    return msg
-
 logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s',
                     level=logging.INFO,
                     datefmt='%m/%d/%Y %H:%M:%S')
@@ -76,7 +30,7 @@ last_slot_time = None
 error_state = False
 last_alert_time = 0
 
-for line in follow(args.logfile):
+for line in misc.follow_file(args.logfile):
     time_now = time.time()
     slot_now = int(time_now) // args.interval_size
 
@@ -101,11 +55,12 @@ for line in follow(args.logfile):
     if not False in intervals[1:]:
         if not error_state or time_now - last_alert_time > ALERT_INTERVAL:
             last_alert_time = time_now
-            feed_handler( create_msg("Log Alert",
-                                     "&#9760;",
-                                     args.logfile,
-                                     "Number of errors exceeded!",
-                                     lines) )
+            misc.feed_handler( args.handler,
+                               misc.create_msg("Log Alert",
+                                               "&#9760;",
+                                               args.logfile,
+                                               "Number of errors exceeded!",
+                                               lines) )
         if not error_state:
             logging.warning("Entering error state!")
             error_state = True
diff --git a/src/misc.py b/src/misc.py
new file mode 100644 (file)
index 0000000..8d8253d
--- /dev/null
@@ -0,0 +1,50 @@
+import logging
+import os
+import shlex
+import subprocess
+import time
+
+def follow_file(path):
+    while True:
+        try:
+            fd = os.open(path, os.O_RDONLY)
+            current_ino = os.fstat(fd).st_ino
+            with os.fdopen(fd, "r") as f:
+                logging.info("Re-attached to file.")
+                for line in f: pass
+                while True:
+                    line = f.readline()
+                    if not line:
+                        if os.stat(path).st_ino != current_ino or \
+                           os.stat(path).st_size < f.tell():
+                            break
+                        else:
+                            time.sleep(1.0)
+                            yield None
+                    else:
+                        yield line.rstrip("\n")
+        except FileNotFoundError:
+            time.sleep(1.0)
+            yield None
+
+def feed_handler(cmd, data):
+    try:
+        handler = subprocess.Popen(shlex.split(cmd),
+                                   stdin=subprocess.PIPE,
+                                   stdout=subprocess.PIPE,
+                                   stderr=subprocess.PIPE,
+                                   encoding='UTF-8')
+        out_data, err_data = handler.communicate("%s\n" % data)
+        if handler.returncode != 0:
+            logging.warning("Handler exited with non-zero return code %d! (%s)" %
+                            (handler.returncode, err_data))
+    except Exception as e:
+        logging.error("Error feeding handler: %s" % str(e))
+
+def create_msg(title, icon, logfile, text, lines):
+    msg = "<b>%s</b> <i>%s</i> %s" % (title, logfile, icon)
+    msg += "<br>%s" % text
+    msg += "<br><pre>"
+    for line in lines: msg += line + "\n"
+    msg += "</pre>"
+    return msg