Commit 2a2a1aab authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

show only log messages of recent days (-D|--days ARG)

This is a legacy commit from before 2015-05-18.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4870
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 3ffb34a4
......@@ -38,6 +38,8 @@
# 18/05/2012 V0.4 provide information regarding possible message
# criticalities (thof)
# 19/05/2012 V0.5 Bug fixed - str.find didn't work as expected.
# 10/12/2012 V0.6 provide '-D ARG' option to list only most recent error
# messages
#
# =============================================================================
"""
......@@ -51,11 +53,12 @@ import re
import smtplib
import logging
import csbacklog
import datetime as dt
from email.mime.text import MIMEText
from collections import deque
__version__ = "V0.5"
__version__ = "V0.6"
__subversion__ = "$Id$"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
......@@ -78,13 +81,14 @@ class Usage(Error):
def display(self):
usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
"\n"+__subversion__+"\nAuthor: "+__author__+ """
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
-H|--host ARG -u|--username ARG -p|--password ARG
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D ARG]
-P|--port ARG -H|--host ARG -u|--username ARG
-p|--password ARG
-r|--receiver ADDRESS [-r|--receiver ADDRESS [...]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -o|--out
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D ARG]
-n|--nagios [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D ARG] -o|--out
[PATH [PATH [...]]]
or: csbackntfy -h|--help\n"""
sys.stderr.write("csbackntfy [line "+self.line+"]: "+self.msg+"\n")
......@@ -97,14 +101,15 @@ def help():
"""
help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
__subversion__+"\nAuthor: "+__author__+"""
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
-H|--host ARG -u|--username ARG -p|--password ARG
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D|--days ARG]
-P|--port ARG -H|--host ARG -u|--username ARG
-p|--password ARG
-r|--receiver ADDRESS [-r|--receiver ADDRESS [...]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -o|--out
[PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D|--days ARG]
-n|--nagios [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] [-D|--days ARG]
-o|--out [PATH [PATH [...]]]
or: csbackntfy -h|--help
-------------------------------------------------------------------------------
-v|--verbose Be verbose.
......@@ -123,6 +128,9 @@ def help():
-n|--nagios Use csbackntfy in it's nagios mode and print the current
status in a simple line to stdout.
-o|--out Send output to stdout instead of sending an email.
-D|--days ARG List only WARNING/ERROR/CRITICAL messages of last ARG days.
If ARG is equal to 0 (zero) then all messages are listed
(default).
PATH Path(s) of the logfile(s) to check. If not specified the
logfiles in /var/log/ were investigated.
-------------------------------------------------------------------------------
......@@ -152,11 +160,11 @@ def main(argv=None):
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:nto", ["help", \
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:ntoD:", ["help", \
"verbose", "debug", "logging", "receiver=", "sender=", "port=", \
"host=", "username=", "password=", 'nagios', 'tls', 'out'])
"host=", "username=", "password=", 'nagios', 'tls', 'out', 'days'])
except getopt.GetoptError as err:
raise Usage(139,err.msg)
raise Usage(167,err.msg)
verbose = False
debugMode = False
receivers = []
......@@ -168,6 +176,7 @@ def main(argv=None):
nagiosMode = False
useTLS = False
stdoutMode = False
daysToList=0
# collect commandline arguments
for opt, arg in opts:
......@@ -200,15 +209,21 @@ def main(argv=None):
useTLS = True
elif opt in ("-o", "--out"):
stdoutMode = True
elif opt in ("-D", "--days"):
daysToList = int(arg)
if daysToList < 0:
raise Usage(215,\
"Invalid argument passed. Value must be equal to or \
\t greater than 0.")
else:
raise Usage(177,"Unhandled option chosen.")
raise Usage(219,"Unhandled option chosen.")
if verbose or debugMode:
logger.addHandler(console)
if 1 <= len(args):
logger.getLogger().info("Taking passed PATH(s) as arguments.")
logFilePathes = [str(arg).rstrip(os.sep)+os.sep for arg in args]
logFilePathes = [str(arg).rstrip(os.sep) for arg in args]
# fetch default logfiles
elif 0 == len(args):
logger.getLogger().info("Taking default logfiles in /var/log/")
......@@ -217,7 +232,14 @@ def main(argv=None):
if None != re.match('^csback\.log$', logfile)]
logFilePathes.reverse()
else:
raise Usage(193,"Invalid argument(s).")
raise Usage(235,"Invalid argument(s).")
# compute time limit for WARNING/ERROR/CRITICAL messages to display
now=dt.datetime.now()
if daysToList != 0:
timeLimit=now-dt.timedelta(days=daysToList)
else:
timeLimit=dt.datetime.min
# use deques so that only the last ten INFO and WARNING messages were
# printed to the mail
......@@ -232,18 +254,24 @@ def main(argv=None):
try:
for path in logFilePathes:
for line in open(path, 'r').readlines():
# extract timestamp from log message
timeStamp=dt.datetime.strptime(str(now.year)+" "+" ".join(str(n) \
for n in line.split()[0:3]),"%Y %b %d %H:%M:%S")
if 'CRITICAL' in line:
criticalList.append("logfile:"+path+"\n"+line)
if timeStamp > timeLimit:
criticalList.append("logfile:"+path+"\n"+line)
elif 'ERROR' in line:
errorList.append("logfile:"+path+"\n"+line)
if timeStamp > timeLimit:
errorList.append("logfile:"+path+"\n"+line)
elif 'WARNING' in line:
warningDeque.appendleft("logfile:"+path+"\n"+line)
if timeStamp > timeLimit:
warningDeque.appendleft("logfile:"+path+"\n"+line)
elif 'INFO' in line:
infoDeque.appendleft("logfile:"+path+"\n"+line)
else:
logger.getLogger().info("Illegal line in logfile found.")
logger.getLogger().info("Illegal line in logfile found: '"+line+"'")
except IOError as err:
raise Error(219, "Error while reading logfiles.")
raise Error(274, "Error while reading logfiles: "+err.filename)
logger.getLogger().debug("Finished reading logfile(s).")
# if nagios mode had been enabled just print the status to stdout
......@@ -261,25 +289,25 @@ def main(argv=None):
if not stdoutMode:
logger.getLogger().debug("Checking email addresses.")
if 0 == len(sender):
raise Usage(236, "Email address of sender missing.")
raise Usage(292, "Email address of sender missing.")
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', sender):
raise Error(239, "Email address of sender not valid.")
raise Error(295, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(241, "Email address of receiver missing.")
raise Usage(297, "Email address of receiver missing.")
for add in receivers:
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', add):
raise Error(245, "Email address of receiver not valid.")
raise Error(301, "Email address of receiver not valid.")
if 0 == len(host):
raise Usage(248, "Hostname missing.")
raise Usage(304, "Hostname missing.")
if 0 == len(username):
raise Usage(250, "Username missing.")
raise Usage(306, "Username missing.")
if 0 == len(password):
raise Usage(252, "Password missing.")
raise Usage(308, "Password missing.")
if -1 == port:
raise Usage(254, "Port missing.")
raise Usage(310, "Port missing.")
# prepare email
logger.getLogger().debug("Preparing content ...")
msg = '============================\n'
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment