Search code examples
pythonpython-watchdog

How to add "user" part with formatting of output message using the watchdog API of Python?


I need to make a function that logs access to a map.
The code is shown below:

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

def FileLogging():
    a = str(input("Give a directory you want to log (vb. D:\\\...\\\ExampleMap): "))
    print("To close the program press ctrl + c.")
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%H:%M:%S')
    path = a
    event_handler = LoggingEventHandler()  
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

FileLogging()

My question is how do I make it so I can add a user in format='%(asctime)s - %(message)s'?

In other words, how can I add the person who changed something in the map/file?

I tried to add %(user)s in format='%(asctime)s - %(message)s' but that doesn't work and gives me the error: KeyError: 'user'.

An example of the output message I get right now is:

14:02:06 - Modified file: D:\\ExampleMap\\text1.txt

I would like to have it as something like this:

14:02:06 - Modified file: D:\\ExampleMap\\text1.txt - SliQ

Solution

  • There is no way to tell who modified a file, hence the watchdog module doesn't support that.