1

I'm only a couple weeks in to learning python with no previous programming background so I apologize for my ignorance..

I'm trying to use a combination of modules to monitor a folder for new files (watchdog), alert on any event (logging module), and then ship the alert to my email (smtplib).

I've found a really good example here: How to run an function when anything changes in a dir with Python Watchdog?

However, I'm stuck trying to save the logging info as a variable to use in my email message. I'm wondering if I'll need to output the logging information to a file and then read in the line to use as a variable.

Anyways, this is what I have. Any help is appreciated. In the meantime I'll continue to Google.

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
import smtplib

class Event(LoggingEventHandler):
    def on_any_event(self, event):
        logMsg = logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

        sender = 'NoReply@myDomain.com'
        receiver = 'test.user@myDomain.com'
        message = """From: No Reply <NoReply@myDomain.com>
        TO: Test User <test.user@myDomain.com>
        Subject: Folder Modify Detected

        The following change was detected: """ + str(logMsg)

        mail = smtplib.SMTP('mailServer.myDomain.com', 25)
        mail.ehlo()
        mail.starttls()
        mail.sendmail(sender, receiver, message)
        mail.close()

if __name__ == "__main__":

    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = Event()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
Community
  • 1
  • 1
Nick Biolo
  • 35
  • 4
  • I mean if you can log it, you know what you are logging right. Simply take that variable out and send it in a mail? – Bobby Jan 19 '17 at 16:48

2 Answers2

0

What you need is a SMTPHandler, so that every time the folder changes (new log created), an email is sent.

import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

class Event(LoggingEventHandler):
    def on_any_event(self, event):
        # do stuff
        pass

if __name__ == "__main__":
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s',
                                  '%Y-%m-%d %H:%M:%S')
    root.setFormatter(formatter)

    mail_handler = logging.handlers.SMTPHandler(mailhost='mailserver',
                                                fromaddr='noreply@example.com',
                                                toaddrs=['me@example.com'],
                                                subject='The log',
                                                credentials=('user','pwd'),
                                                secure=None)
    mail_handler.setLevel(logging.INFO)
    mail_handler.setFormatter(formatter)
    root.addHandler(mail_handler) # Add this handler to root logger

    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = Event()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
Shane
  • 1,793
  • 1
  • 8
  • 17
  • Thanks for the replies. I was able to get this working with the example I found here: https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory. – Nick Biolo Jan 24 '17 at 21:55
0

Was able to obtain working example here and tailor to my needs: https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory

Nick Biolo
  • 35
  • 4