python日志:多个日志记录器

2024-04-18 20:25:46 发布

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

我有一个名为Job的对象,它有自己的记录器(每个作业都需要一个日志文件,该文件由日志记录.getLogger())

问题是我创造了数千个工作岗位(约4000个),他们都想创造一个记录者。你知道吗

Traceback (most recent call last):
  File "/u/lib/btool/Job.py", line 151, in __init__
  File "/usr/lib/python2.7/logging/__init__.py", line 911, in __init__
  File "/usr/lib/python2.7/logging/__init__.py", line 936, in _open
IOError: [Errno 24] Too many open files: '/x/zooland/20160710-032802.log'

有办法对付多个伐木工人吗?你知道吗


Tags: 文件对象inpyinitlibusrlogging
1条回答
网友
1楼 · 发布于 2024-04-18 20:25:46

下面是一个自定义文件处理程序,它存储日志消息,然后关闭文件。你知道吗

import logging


class MyFileHandler(logging.Handler):
    def __init__(self, filename):
        self.filename = filename
        super().__init__()

    def emit(self, record):
        log_text = self.format(record)
        try:
            fh = open(self.filename, "a")
            fh.write(log_text)
            fh.close()

            return True
        except:
            return False


logger = logging.getLogger("job")

handler = MyFileHandler("file-1")
logger.addHandler(handler)

logger.error("hola")

相关问题 更多 >