From 171553677c5dfdc2c3e06980b90c76aa6577f15d Mon Sep 17 00:00:00 2001 From: Thomas Steen Rasmussen Date: Thu, 23 Mar 2017 18:32:13 +0100 Subject: [PATCH] fixup logging --- src/bornhack/settings.py | 30 ++++++++++++------- src/camps/models.py | 7 +++-- src/camps/views.py | 15 ++++++++-- src/ircbot/irc3module.py | 26 +++++++--------- .../commands/notification_worker.py | 5 +++- src/shop/email.py | 11 ++++--- src/shop/epayintegration.py | 17 ++++++----- src/shop/pdf.py | 5 +++- src/shop/views.py | 21 +++++++------ src/utils/models.py | 4 ++- 10 files changed, 86 insertions(+), 55 deletions(-) diff --git a/src/bornhack/settings.py b/src/bornhack/settings.py index bcb78bf1..c8cae8e4 100644 --- a/src/bornhack/settings.py +++ b/src/bornhack/settings.py @@ -113,22 +113,30 @@ if DEBUG: LOGGING = { 'version': 1, 'disable_existing_loggers': False, - 'handlers': { - 'mail_admins': { - 'level': 'ERROR', - 'class': 'django.utils.log.AdminEmailHandler', + 'formatters': { + 'syslog': { + 'format': '%(levelname)s %(name)s.%(funcName)s(): %(message)s' }, 'console': { - 'level':'DEBUG', - 'class':'logging.StreamHandler', + 'format': '[%(asctime)s] %(name)s.%(funcName)s() %(levelname)s %(message)s', + 'datefmt': '%d/%b/%Y %H:%M:%S' + }, + }, + 'handlers': { + 'console': { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'console' }, }, 'loggers': { - 'django.request': { - 'handlers': ['mail_admins'], - 'level': 'ERROR', - 'propagate': True, + # send bornhack logger to both console and syslog at DEBUG level, and + # do not propagate bornhack.* messages up to the root logger + 'bornhack': { + 'handlers': ['console'], + 'level': 'DEBUG', + 'propagate': False, }, - } + }, } diff --git a/src/camps/models.py b/src/camps/models.py index 09239332..74d3d37f 100644 --- a/src/camps/models.py +++ b/src/camps/models.py @@ -7,6 +7,9 @@ from django.core.exceptions import ValidationError from datetime import timedelta from django.utils import timezone from django.urls import reverse +import logging +logger = logging.getLogger("bornhack.%s" % __name__) + class Camp(CreatedUpdatedModel, UUIDModel): @@ -98,13 +101,13 @@ class Camp(CreatedUpdatedModel, UUIDModel): Returns a list of DateTimeTZRanges representing the days during the specified part of the camp. ''' if not hasattr(self, camppart): - print("nonexistant field/attribute") + logger.error("nonexistant field/attribute") return False field = getattr(self, camppart) if not hasattr(field, '__class__') or not hasattr(field.__class__, '__name__') or not field.__class__.__name__ == 'DateTimeTZRange': - print("this attribute is not a datetimetzrange field: %s" % field) + logger.error("this attribute is not a datetimetzrange field: %s" % field) return False daycount = (field.upper - field.lower).days diff --git a/src/camps/views.py b/src/camps/views.py index 243dd424..cb791338 100644 --- a/src/camps/views.py +++ b/src/camps/views.py @@ -5,26 +5,35 @@ from django.shortcuts import redirect from .mixins import CampViewMixin from django.views import View from django.conf import settings +import logging +logger = logging.getLogger("bornhack.%s" % __name__) class CampRedirectView(CampViewMixin, View): def dispatch(self, request, *args, **kwargs): # find the closest camp in the past prevcamp = Camp.objects.filter(camp__endswith__lt=timezone.now()).order_by('-camp')[0] + # find the closest upcoming camp nextcamp = Camp.objects.filter(camp__startswith__gt=timezone.now()).order_by('camp')[0] + # find the number of days between the two camps daysbetween = (nextcamp.camp.lower - prevcamp.camp.upper).days + # find the number of days since the last camp ended dayssinceprevcamp = (timezone.now() - prevcamp.camp.lower).days + # find the percentage of time passed percentpassed = (dayssinceprevcamp / daysbetween) * 100 - print(daysbetween, dayssinceprevcamp, percentpassed) + # do the redirect if percentpassed > settings.CAMP_REDIRECT_PERCENT: - return redirect(kwargs['page'], camp_slug=nextcamp.slug) + camp = nextcamp else: - return redirect(kwargs['page'], camp_slug=prevcamp.slug) + camp = prevcamp + + logger.debug("Redirecting to camp '%s' for page '%s' because %s%% of the time between the camps passed" % (camp.slug, kwargs['page'], int(percentpassed))) + return redirect(kwargs['page'], camp_slug=camp.slug) class CampDetailView(DetailView): diff --git a/src/ircbot/irc3module.py b/src/ircbot/irc3module.py index a2f512b5..eccca210 100644 --- a/src/ircbot/irc3module.py +++ b/src/ircbot/irc3module.py @@ -2,6 +2,8 @@ import irc3 from ircbot.models import OutgoingIrcMessage from django.conf import settings from django.utils import timezone +import logging +logger = logging.getLogger("bornhack.%s" % __name__) @irc3.plugin @@ -24,20 +26,17 @@ class Plugin(object): def server_ready(self, **kwargs): """triggered after the server sent the MOTD (require core plugin)""" - if settings.DEBUG: - print("inside server_ready(), kwargs: %s" % kwargs) + logger.debug("inside server_ready(), kwargs: %s" % kwargs) def connection_lost(self, **kwargs): """triggered when connection is lost""" - if settings.DEBUG: - print("inside connection_lost(), kwargs: %s" % kwargs) + logger.debug("inside connection_lost(), kwargs: %s" % kwargs) def connection_made(self, **kwargs): """triggered when connection is up""" - if settings.DEBUG: - print("inside connection_made(), kwargs: %s" % kwargs) + logger.debug("inside connection_made(), kwargs: %s" % kwargs) ############################################################################################### @@ -46,8 +45,7 @@ class Plugin(object): @irc3.event(irc3.rfc.JOIN_PART_QUIT) def on_join_part_quit(self, **kwargs): """triggered when there is a join part or quit on a channel the bot is in""" - if settings.DEBUG: - print("inside on_join_part_quit(), kwargs: %s" % kwargs) + logger.debug("inside on_join_part_quit(), kwargs: %s" % kwargs) if self.bot.nick == kwargs['mask'].split("!")[0] and kwargs['channel'] == "#tirsdagsfilm": self.bot.loop.call_later(1, self.bot.get_outgoing_messages) @@ -55,14 +53,12 @@ class Plugin(object): @irc3.event(irc3.rfc.PRIVMSG) def on_privmsg(self, **kwargs): """triggered when a privmsg is sent to the bot or to a channel the bot is in""" - if settings.DEBUG: - print("inside on_privmsg(), kwargs: %s" % kwargs) + logger.debug("inside on_privmsg(), kwargs: %s" % kwargs) @irc3.event(irc3.rfc.KICK) def on_kick(self, **kwargs): - if settings.DEBUG: - print("inside on_kick(), kwargs: %s" % kwargs) + logger.debug("inside on_kick(), kwargs: %s" % kwargs) ############################################################################################### ### custom irc3 methods @@ -73,7 +69,7 @@ class Plugin(object): This method gets unprocessed OutgoingIrcMessage objects and attempts to send them to the target channel. Messages are skipped if the bot is not in the channel. """ - print("inside get_outgoing_messages()") + logger.debug("inside get_outgoing_messages()") for msg in OutgoingIrcMessage.objects.filter(processed=False).order_by('created'): # if this message expired mark it as expired and processed without doing anything if msg.timeout < timezone.now(): @@ -85,7 +81,7 @@ class Plugin(object): # is this message for a channel or a nick? if msg.target[0] == "#" and msg.target in self.bot.channels: - print("sending privmsg to %s: %s" % (msg.target, msg.message)) + logger.debug("sending privmsg to %s: %s" % (msg.target, msg.message)) self.bot.privmsg(msg.target, msg.message) msg.processed=True msg.save() @@ -94,7 +90,7 @@ class Plugin(object): msg.processed=True msg.save() else: - print("skipping message to %s" % msg.target) + logger.warning("skipping message to %s" % msg.target) # call this function again in 60 seconds self.bot.loop.call_later(settings.IRCBOT_CHECK_MESSAGE_INTERVAL_SECONDS, self.bot.get_outgoing_messages) diff --git a/src/program/management/commands/notification_worker.py b/src/program/management/commands/notification_worker.py index 185e4ba2..57115ea7 100644 --- a/src/program/management/commands/notification_worker.py +++ b/src/program/management/commands/notification_worker.py @@ -8,6 +8,9 @@ from camps.utils import get_current_camp from django.utils import timezone from program.models import EventInstance from datetime import timedelta +import logging +logger = logging.getLogger("bornhack.%s" % __name__) + class Command(BaseCommand): @@ -36,7 +39,7 @@ class Command(BaseCommand): message="starting soon: %s" % ei, timeout=ei.when.lower ) - print("added irc message id %s for eventinstance %s" % (oim.id, ei)) + logger.info("added irc message id %s for eventinstance %s" % (oim.id, ei)) ei.notifications_sent=True ei.save() diff --git a/src/shop/email.py b/src/shop/email.py index 8d82e818..5c22f603 100644 --- a/src/shop/email.py +++ b/src/shop/email.py @@ -1,6 +1,9 @@ from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.template.loader import render_to_string +import logging +logger = logging.getLogger("bornhack.%s" % __name__) + def send_email(emailtype, recipient, formatdict, subject, sender='BornHack ', attachment=None): @@ -18,13 +21,13 @@ def send_email(emailtype, recipient, formatdict, subject, sender='BornHack