Add logging to stdout when enabled to facilitate debugging issues.

This commit is contained in:
Christopher Broderick 2023-10-24 13:49:56 +01:00
parent 79150c74d2
commit 8849943d33
2 changed files with 32 additions and 6 deletions

View File

@ -39,6 +39,7 @@ import sys
from time import ctime
import typing
from typing import List
import traceback
# import User model, which may be a custom model
@ -56,11 +57,17 @@ STRIPPED_SUBJECT_STRINGS = [
HTML_EMAIL_ATTACHMENT_FILENAME = _("email_html_body.html")
def process_email(quiet=False):
def process_email(quiet: bool =False, debug_to_stdout=False):
if debug_to_stdout:
print("Extracting email into queues...")
q: Queue() # Typing ahead of time for loop to make it more useful in an IDE
for q in Queue.objects.filter(
email_box_type__isnull=False,
allow_email_submission=True):
log_msg = f"Processing queue: {q.slug} Email address: {q.email_address}..."
if debug_to_stdout:
print(log_msg )
logger = logging.getLogger('django.helpdesk.queue.' + q.slug)
logging_types = {
'info': logging.INFO,
@ -84,16 +91,25 @@ def process_email(quiet=False):
logger.addHandler(log_file_handler)
else:
log_file_handler = None
try:
if not q.email_box_last_check:
q.email_box_last_check = timezone.now() - timedelta(minutes=30)
try:
queue_time_delta = timedelta(minutes=q.email_box_interval or 0)
if (q.email_box_last_check + queue_time_delta) < timezone.now():
process_queue(q, logger=logger)
q.email_box_last_check = timezone.now()
q.save()
log_msg: str = f"Queue successfully processed: {q.slug}"
if logger.isEnabledFor(logger.INFO):
logger.info(log_msg)
if debug_to_stdout:
print(log_msg )
except Exception as e:
logger.error("Queue processing failed: {q.slug}", exc_info=True)
if debug_to_stdout:
print(f"Queue processing failed: {q.slug}" )
print("-"*60)
traceback.print_exc(file=sys.stdout)
finally:
# we must close the file handler correctly if it's created
try:
@ -106,6 +122,8 @@ def process_email(quiet=False):
logger.removeHandler(log_file_handler)
except Exception as e:
logging.exception(e)
if debug_to_stdout:
print("Email extraction into queues completed.")
def pop3_sync(q, logger, server):

View File

@ -30,10 +30,18 @@ class Command(BaseCommand):
default=False,
help='Hide details about each queue/message as they are processed',
)
parser.add_argument(
'--debug_to_stdout',
action='store_true',
dest='debug_to_stdout',
default=False,
help='Log additional messaging to stdout.',
)
def handle(self, *args, **options):
quiet = options.get('quiet', False)
process_email(quiet=quiet)
debug_to_stdout = options.get('debug_to_stdout', False)
process_email(quiet=quiet, debug_to_stdout=debug_to_stdout)
if __name__ == '__main__':