首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >已配置Logger时在线程内进行日志记录

已配置Logger时在线程内进行日志记录
EN

Stack Overflow用户
提问于 2020-05-09 20:47:16
回答 1查看 145关注 0票数 0

编辑:Repo with all code (分支"daemon")。问题是关于链接到的文件中的代码)。

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

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

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

代码语言:javascript
复制
    with daemon.DaemonContext(
        pidfile=daemon.pidfile.PIDLockFile(self.pid_file),
        stderr=self.log_file,
        stdout=self.log_file
    ):
        self.watch_files()

其中self.log_file是我为写入而打开的文件。

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

代码语言:javascript
复制
--- 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

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

EN

回答 1

Stack Overflow用户

发布于 2020-05-17 00:51:25

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

代码语言:javascript
复制
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设置为文件日志处理程序,因此一旦切换上下文,它就不会关闭文件。这是原始problem.
  2. Further的实际解决方案,但是,这两个方法都需要在单独的线程中,而不是只在一个线程中。主线程中的while True循环阻止了另一个方法的运行,因此将它们放在单独的线程中意味着它们都可以运行
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61696936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档