abhidoeslinux
abhidoeslinux

Reputation: 151

What is the best way to send python console output as email from within the script?

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.

Upvotes: 3

Views: 2908

Answers (2)

gplayer
gplayer

Reputation: 1811

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).

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174662

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('[email protected]',
                            ('[email protected]',),
                            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.')

Upvotes: 5

Related Questions