0

I have currently using logging which sends any error to email.

#EMAIL AN ERROR
logging.getLogger('googleapiclient.discovery').setLevel(logging.WARNING)
smtp_handler = logging.handlers.SMTPHandler(mailhost=(config.EMAIL_HOST, config.EMAIL_PORT),
                                            fromaddr=config.EMAIL_FROM, 
                                            toaddrs=config.EMAIL_TO, 
                                            subject=config.EMAIL_SUBJECT) 
logger = logging.getLogger()
logger.addHandler(smtp_handler)

What is the clean way to add an extra logging section with will save all messages logger.info("SAMPLE") to the log file which will be in the same folder as python scripts?

This is basicConfig which I have trying to use, but not sure how to combine Logging errors to email and logger.info() save to file?

#LOGGING TO THE FILE
logging.basicConfig(filename=config.LOG_FILE,
                            filemode='w',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.INFO)

I'm looking for:

1) All logger.info() will be saved to the file BUT NOT EMAILED.

2) Warnings + will be sent to the email address as well as saved to the file

  • Why people mark as a minus? as there is not a straightforward answer? –  Oct 15 '18 at 13:15

1 Answers1

0

What you want can be accomplished fairly easily using basic Python file handling techniques. In a nutshell you open the file, overwrite or append to the file depending on what you want, then close the file at the end of the script. Here are some resources to help you get started:

https://www.pythonforbeginners.com/cheatsheet/python-file-handling https://docs.python.org/3/tutorial/inputoutput.html (section 7.2)

What you want will ultimately end up looking something like this:

logfile = open("logging.INFO", "a")
logfile.writelines("Stuff you want to log goes here. \n")
logfile.close
Matthew
  • 768
  • 1
  • 11
  • 25
  • Yes, that's true, I know how to do it BUT this not CLEAN way, based on research the clean way is to use LOGGING and \i'm not sure how to combine it correctly so it email and save in the way I wrote. –  Oct 15 '18 at 13:33
  • - have a look, https://stackoverflow.com/questions/11574257/how-do-i-write-log-messages-to-a-log-file-and-the-console-at-the-same-time –  Oct 15 '18 at 13:39
  • It doesn't get any cleaner than open, write, and close. :P That is the minimum amount of steps involved. I don't use the logging module, I always write my own logging. – Matthew Oct 15 '18 at 13:41
  • It looks like your application already has a logging scheme built in... But if it doesn't do what you want, you will have to write your own logging. You might be able to add a hack that simply opens the logging.INFO and writes to it every time an e-mail is sent. – Matthew Oct 15 '18 at 14:04