已配置记录器时在线程内记录日志

2024-09-28 01:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:Repo with all code(分支“守护进程”)。问题是关于链接到的文件中的代码)

我的主程序如下配置日志记录(选项已简化):

logging.basicConfig(level='DEBUG', filename="/some/directory/cstash.log")

我的应用程序的一部分启动了一个守护进程,为此我使用了daemon包:

    with daemon.DaemonContext(
        pidfile=daemon.pidfile.PIDLockFile(self.pid_file),
        stderr=self.log_file,
        stdout=self.log_file
    ):
        self.watch_files()

其中self.log_file是我打开准备编写的文件

启动应用程序时,我得到:

--- Logging error ---
Traceback (most recent call last):
  File "/Users/afraz/.pyenv/versions/3.7.2/lib/python3.7/logging/__init__.py", line 1038, in emit
    self.flush()
  File "/Users/afraz/.pyenv/versions/3.7.2/lib/python3.7/logging/__init__.py", line 1018, in flush
    self.stream.flush()
OSError: [Errno 9] Bad file descriptor

如果我关闭了对守护进程中某个文件的日志记录,则主应用程序中的日志记录工作正常;如果我关闭了对主应用程序中某个文件的日志记录,则守护进程中的日志记录工作正常。如果我将它们设置为登录到一个文件(甚至是不同的文件),就会出现上述错误


Tags: 文件selflog应用程序进程loggingwith记录
1条回答
网友
1楼 · 发布于 2024-09-28 01:58:05

在尝试了许多方法之后,以下是有效的方法:

def process_wrapper():
    with self.click_context:
        self.process_queue()

def watch_wrapper():
    with self.click_context:
        self.watch_files()

with daemon.DaemonContext(
    pidfile=daemon.pidfile.PIDLockFile(self.pid_file),
    files_preserve=[logger.handlers[0].stream.fileno()],
    stderr=self.log_file,
    stdout=self.log_file
):
    logging.info("Started cstash daemon")

    while True:
        threading.Thread(target=process_wrapper).start()
        time.sleep(5)
        threading.Thread(target=watch_wrapper).start()

有两个主要问题:

  1. daemon.DaemonContext需要将files_preserve设置为文件日志处理程序,以便在切换上下文后不会关闭文件。这是原始问题的实际解决方案
  2. 然而,更进一步地说,这两种方法都需要在单独的线程中,而不仅仅是一个线程。主线程中的while True循环正在停止另一个方法的运行,因此将它们放在单独的线程中意味着它们都可以运行

相关问题 更多 >

    热门问题