3

I have a python script that does multiple things and prints logs on the console. For now, I have not used any logging mechanism(I am just printing the required messages using print) How do I take all the prints and send it out as an email? Do I have to save it all in a variable and pass it to smtplib? or is there a better way?

Sample code

for job in fetch.getJobStats():
        if job['userName']+"_"+job['tenantId'] in summaryTotal:
            summary = summaryTotal[job['userName']+"_"+job['tenantId']]
        else:
            summary = Summary(job['userName'], job['tenantId'])
            summaryTotal[summary.user+"_"+summary.tenant] = summary

        summary.jobs.append(Job(job['jobId'], job['jobStatus'], int(job['fileSize'])))
        totalBw += int(job['fileSize'])

    print("Cumulative Size: " + str(totalBw))
    for summaryKey in summaryTotal.keys():
        summary = summaryTotal[summaryKey]

        inprogress = []
        failed = []
        completed = []
        cancelled = []
        totalBwTenantUser = 0

        for job in summary.jobs:
            totalBwTenantUser += job.filesize
            if job.status == "JOBCANCELLED":
                cancelled.append(job.id)
            elif job.status == "JOBCOMPLETED":
                completed.append(job.id)
            elif job.status == "INPROGRESS":
                completed.append(job.id)
            elif job.status == "JOBFAILED":
                completed.append(job.id)

        print("-" * 50)
        print("Tenant: " + summary.tenant)
        print("User  : " + summary.user)
        print("Size    : " + str(totalBwTenantUser))
        print("\n")
        print("INPROGRESS: " + str(inprogress))
        print("COMPLETED : " + str(completed))
        print("CANCELLED : " + str(cancelled))
        print("FAILED    : " + str(failed))
        print("-" * 50)

All the prints should be shot off an email.

abhidoeslinux
  • 141
  • 3
  • 10
  • Please post your code and way you are saving them, and someone can help you with sending email – MohitC Oct 19 '15 at 06:22

2 Answers2

5

You really should use the excellent logging system that comes with Python.

Combine it with the mailinglogger handler and you have everything you need:

import logging

from mailinglogger.SummarisingLogger import SummarisingLogger

handler = SummarisingLogger('from@example.com',
                            ('to@example.com',),
                            subject='[LOGS] %s (hostname)s',
                            mailhost='smtp.example.com')

logging.basicConfig(format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.INFO)
logger = logging.getLogger()
logger.addHandler(handler)

logging.info('Sent by email.')
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
2

I would use the logging library, configure the logging to a file then just read the contents of that file and send it or attach the log file directly to the email you're sending (see How to send email attachments with Python).

Community
  • 1
  • 1
gplayer
  • 1,741
  • 1
  • 14
  • 15
  • 1
    python looging library also provides an [SMTPHandler](https://docs.python.org/2/library/logging.handlers.html#smtphandler). You can use this to send mail instead of attaching your log file directly. – shanmuga Oct 19 '15 at 06:31
  • Thanks, I did not know that! – gplayer Oct 19 '15 at 06:45