reworked logger class - also handles bot crashes and tbs now. added configline for log directory.

This commit is contained in:
b3yond 2018-01-05 10:42:31 +01:00
parent 8357be7f7d
commit 654af44534
6 changed files with 70 additions and 86 deletions

View file

@ -28,6 +28,8 @@ passphrase = "sup3rs3cur3"
# when it breaks down), you should specify a contact email address:
#contact = "your_mail@riseup.net"
[logging]
logpath = "logs"
# [trigger]
# goodlists are one regex per line.

View file

@ -2,18 +2,40 @@
import os
import datetime
import traceback
import sys
import sendmail
class Logger(object):
"""
builds log files, writes the log messages.
If a critical error occurs, handles the bugtracking and error
messages.
"""
def __init__(self, logpath=None):
def __init__(self, config):
"""
logs everything & sends bugtracking messages.
:param config: config file
"""
self.config = config
# initialize logging
if logpath:
self.logpath = logpath
if config["logging"]["logpath"]:
self.logpath = os.path.join(self.config["logging"]["logpath"], str(datetime.datetime.now()))
else:
self.logpath = os.path.join("logs", str(datetime.datetime.now()))
print("Path of logfile: " + self.logpath)
# intialize shutdown contact
try:
self.no_shutdown_contact = False
self.contact = self.config['mail']['contact']
except KeyError:
self.no_shutdown_contact = True
def log(self, message):
"""
Writing an error message & sometimes a traceback to a logfile in logs/
@ -30,3 +52,29 @@ class Logger(object):
self.log("Failed to save log message due to UTF-8 error. ")
print(line, end="")
def generate_tb(self, exc):
tb = traceback.extract_tb(exc[2]) # returns StackSummary object
tb = "\n".join(tb.format()) # string of the actual traceback
message = ("Traceback (most recent call last):\n",
tb,
exc[0].__name__) # the type of the Exception
message = "".join(message) # concatenate to full traceback message
return message
def shutdown(self, tb):
""" If something breaks, it shuts down the bot and messages the owner.
:param tb: (string) traceback
"""
logmessage = "Shit went wrong, closing down.\n" + tb + "\n\n"
if self.no_shutdown_contact:
self.log(logmessage)
return
logmessage = logmessage + "Sending message to " + self.contact
self.log(logmessage)
try:
mailer = sendmail.Mailer(self.config)
mailer.send(tb, self.contact, "Ticketfrei Crash Report")
except:
self.log(self.generate_tb(sys.exc_info()))
print()

View file

@ -8,15 +8,13 @@ import re
import time
import trigger
import logger
import sendmail
import traceback
import sys
class RetootBot(object):
def __init__(self, config, filter, logger):
def __init__(self, config, trigger, logger):
self.config = config
self.filter = filter
self.trigger = trigger
self.client_id = self.register()
self.m = self.login()
@ -27,13 +25,6 @@ class RetootBot(object):
except IOError:
self.seen_toots = set()
# intialize shutdown contact
try:
self.no_shutdown_contact = False
self.contact = self.config['mail']['contact']
except KeyError:
self.no_shutdown_contact = True
self.logger = logger
def register(self):
@ -75,7 +66,7 @@ class RetootBot(object):
self.seen_toots.add(notification['status']['id'])
text_content = re.sub(r'<[^>]*>', '',
notification['status']['content'])
if not self.filter.is_ok(text_content):
if not self.trigger.is_ok(text_content):
continue
self.logger.log('Boosting toot from %s: %s' % (
# notification['status']['id'],
@ -95,25 +86,6 @@ class RetootBot(object):
# return mentions for mirroring
return retoots
def shutdown(self, tb):
""" If something breaks, it shuts down the bot and messages the owner.
"""
logmessage = "Shit went wrong, closing down.\n" + tb + "\n\n"
if self.no_shutdown_contact:
self.logger.log(logmessage)
return
logmessage = logmessage + "Sending message to " + self.contact
self.logger.log(logmessage)
# feature yet only in RetweetBot:
# self.save_last_mention()
try:
mailer = sendmail.Mailer(self.config)
mailer.send(tb, self.contact, "Ticketfrei Crash Report")
except:
# traceback.print_exc()
self.logger.log(traceback.extract_tb(sys.exc_info()[2]))
print()
if __name__ == '__main__':
# read config in TOML format (https://github.com/toml-lang/toml#toml)
@ -121,7 +93,7 @@ if __name__ == '__main__':
config = toml.load(configfile)
trigger = trigger.Trigger(config)
logger = logger.Logger()
logger = logger.Logger(config)
bot = RetootBot(config, trigger, logger)
@ -133,11 +105,6 @@ if __name__ == '__main__':
print("Good bye. Remember to restart the bot!")
except:
exc = sys.exc_info() # returns tuple [Exception type, Exception object, Traceback object]
tb = traceback.extract_tb(exc[2]) # returns StackSummary object
tb = "\n".join(tb.format()) # string of the actual traceback
message = ("Traceback (most recent call last):\n",
tb,
exc[0].__name__) # the type of the Exception
message = "".join(message) # concatenate to full traceback message
message = logger.generate_tb(exc)
bot.logger.log(message)
bot.shutdown(message)
bot.logger.shutdown(message)

View file

@ -6,9 +6,7 @@ import requests
import pytoml as toml
import trigger
from time import sleep
import traceback
import logger
import sendmail
class RetweetBot(object):
@ -216,26 +214,6 @@ class RetweetBot(object):
# Return Retweets for tooting on mastodon
return mastodon
def shutdown(self, tb):
""" If something breaks, it shuts down the bot and messages the owner.
:param tb: (string) traceback
"""
logmessage = "Shit went wrong, closing down.\n" + tb + "\n\n"
if self.no_shutdown_contact:
self.logger.log(logmessage)
return
logmessage = logmessage + "Sending message to " + self.contact
self.logger.log(logmessage)
self.save_last_mention()
try:
mailer = sendmail.Mailer(self.config)
mailer.send(tb, self.contact, "Ticketfrei Crash Report")
except:
# traceback.print_exc()
self.logger.log(traceback.extract_tb(sys.exc_info()[2]))
print()
if __name__ == "__main__":
# create an Api object
@ -243,7 +221,7 @@ if __name__ == "__main__":
config = toml.load(configfile)
trigger = trigger.Trigger(config)
logger = logger.Logger()
logger = logger.Logger(config)
bot = RetweetBot(trigger, config, logger)
try:
@ -254,11 +232,7 @@ if __name__ == "__main__":
print("Good bye. Remember to restart the bot!")
except:
exc = sys.exc_info() # returns tuple [Exception type, Exception object, Traceback object]
tb = traceback.extract_tb(exc[2]) # returns StackSummary object
tb = "\n".join(tb.format()) # string of the actual traceback
message = ("Traceback (most recent call last):\n",
tb,
exc[0].__name__) # the type of the Exception
message = "".join(message) # concatenate to full traceback message
message = logger.generate_tb(exc)
bot.logger.log(message)
bot.shutdown(message)
bot.save_last_mention()
bot.logger.shutdown(message)

View file

@ -43,6 +43,7 @@ class Mailer(object):
return "Sent mail to " + recipient + ": " + subject
# For testing:
if __name__ == '__main__':
# read config in TOML format (https://github.com/toml-lang/toml#toml)

View file

@ -3,10 +3,7 @@
import pytoml as toml
import logger
import time
import traceback
import os
import sys
import datetime
from retootbot import RetootBot
from retweetbot import RetweetBot
@ -20,8 +17,7 @@ if __name__ == '__main__':
trigger = Trigger(config)
logpath = os.path.join("logs", str(datetime.datetime.now()))
logger = logger.Logger(logpath)
logger = logger.Logger(config)
mbot = RetootBot(config, trigger, logger)
tbot = RetweetBot(trigger, config, logger)
@ -36,11 +32,7 @@ if __name__ == '__main__':
print("Good bye. Remember to restart the bot!")
except:
exc = sys.exc_info() # returns tuple [Exception type, Exception object, Traceback object]
tb = traceback.extract_tb(exc[2]) # returns StackSummary object
tb = "\n".join(tb.format()) # string of the actual traceback
message = ("Traceback (most recent call last):\n",
tb,
exc[0].__name__) # the type of the Exception
message = "".join(message) # concatenate to full traceback message
message = logger.generate_tb(exc)
tbot.logger.log(message)
tbot.shutdown(message)
tbot.save_last_mention()
tbot.logger.shutdown(message)