3

I am using python-watchdog to monitor certain paths for changes like add, delete, modify, etc. Along with the time and message information, I want to capture the username of the user who made that change. I was looking at getpass, and I looked around for a variable within logging itself, but wasnt able to find anything.

Any clues? My watchdog code is below

print 'starting the watcher mate...'
create_log_file()
logging.basicConfig(filename = log_file, level = logging.INFO, format = '%(asctime)s - %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '/etc/nginx/'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
Abhay Bhargav
  • 399
  • 1
  • 5
  • 15

1 Answers1

4

Update

I was able to solve my problem thusly. I solved the problem using Method-Overriding. I created another class in my python script called MyLoggingEventHandler and included the user's name using the getpass.getuser() function. Now, I am able to get details of the user in my log statements.

Code

class MyLoggingEventHandler(LoggingEventHandler):

    def on_moved(self, event):
            super(LoggingEventHandler, self).on_moved(event)
            what = 'directory' if event.is_directory else 'file'
            logging.info("Moved %s: from %s to %s, by %s", what, event.src_path, event.dest_path, getpass.getuser())

    def on_created(self, event):
            super(LoggingEventHandler, self).on_created(event)
            what = 'directory' if event.is_directory else 'file'
            logging.info("Created %s: %s, by %s", what, event.src_path, getpass.getuser())

    def on_deleted(self, event):
            super(LoggingEventHandler, self).on_deleted(event)
            what = 'directory' if event.is_directory else 'file'
            logging.info("Deleted %s: %s, by %s", what, event.src_path, getpass.getuser())

    def on_modified(self, event):
            super(LoggingEventHandler, self).on_modified(event)
            what = 'directory' if event.is_directory else 'file'
            logging.info("Modified %s: %s, by %s", what, event.src_path, getpass.getuser())

These are 2 lines from my log file.

2016-04-17 15:23:16 - Modified file: /path/to/file.txt, by myusername - 
2016-04-17 15:23:19 - Modified file: /path/to/file2.txt, by myusername -
Abhay Bhargav
  • 399
  • 1
  • 5
  • 15
  • 2
    The username can't change during run time, so you can make your class more efficient. Call `getpass.getuser()` in the `__init__` method and save it as an instance attribute for the other methods to access. – PM 2Ring Apr 17 '16 at 10:07
  • @PM2Ring - Agreed. Will do. Thanks! – Abhay Bhargav Apr 17 '16 at 10:09
  • 1
    This will only return the local username running the console. My watchdog monitor a file share, how can i return the client username/hostname? – ChristianG Jul 18 '17 at 07:23