如何在python的日志库中捕获OS用户的用户名?

How to capture the OS user's username using in python's logging library?

本问题已经有最佳答案,请猛点这里访问。

我使用python-watchdog来监视某些路径的更改,如添加、删除、修改等。除了时间和消息信息外,我还想捕获进行更改的用户的用户名。我在查看getpass,四处查看日志本身中的变量,但找不到任何内容。

有什么线索吗?我的看门狗代码在下面

1
2
3
4
5
6
7
8
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()


更新

我彻底解决了我的问题。我用重写方法解决了这个问题。我在python脚本中创建了另一个名为myloggingEventHandler的类,并使用getpass.getuser()函数包含了用户的名称。现在,我可以在日志语句中获取用户的详细信息。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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())

这是我日志文件中的两行。

1
2
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 -