【问题标题】:Logging using multiprocessing使用多处理记录
【发布时间】:2012-05-19 12:16:54
【问题描述】:

我确实有以下 logger 类(作为 logger.py):

import logging, logging.handlers
import config

log = logging.getLogger('myLog')

def start():
    "Function sets up the logging environment."
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter(fmt='%(asctime)s [%(levelname)s] %(message)s', datefmt='%d-%m-%y %H:%M:%S')

    if config.logfile_enable:
        filehandler = logging.handlers.RotatingFileHandler(config.logfile_name, maxBytes=config.logfile_maxsize,backupCount=config.logfile_backupCount)
        filehandler.setLevel(logging.DEBUG)
        filehandler.setFormatter(formatter)
        log.addHandler(filehandler)

    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    console.setFormatter(logging.Formatter('[%(levelname)s] %(message)s')) # nicer format for console
    log.addHandler(console)

    # Levels are: debug, info, warning, error, critical.
    log.debug("Started logging to %s [maxBytes: %d, backupCount: %d]" % (config.logfile_name, config.logfile_maxsize, config.logfile_backupCount))

def stop():
    "Function closes and cleans up the logging environment."
    logging.shutdown()

对于日志记录,我启动一次logger.start(),然后在任何项目文件中导入from logger import log。然后我只在需要时使用log.debug()log.error()。 它在脚本的任何地方都可以正常工作(不同的类、函数和文件),但它不适用于通过多处理类启动的不同进程。

我收到以下错误:No handlers could be found for logger "myLog"

我能做什么?

【问题讨论】:

  • 你在哪里初始化“第二个”进程,第二个进程是否执行代码的upside sn-p?
  • 嗯,第二个过程我没有再次初始化。为什么找不到处理程序是有道理的。但我不能将不同的记录器对象集成到同一个文件中,并期望两个对象都能正确记录。还是我错了?
  • 也许这是相关的? docs.python.org/howto/…
  • @Not_a_Golfer 谢谢。请将其发布为答案,以便我可以选择它。

标签: python logging multiprocessing


【解决方案1】:

来自 python 文档:logging to a single file from multiple processes is not supported, because there is no standard way to serialize access to a single file across multiple processes in Python.

见:http://docs.python.org/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

顺便说一句:我在这种情况下所做的是使用 Scribe,它是一个分布式日志聚合器,我通过 TCP 登录。这使我可以将所有服务器记录到同一个地方,而不仅仅是所有进程。

查看此项目:http://pypi.python.org/pypi/ScribeHandler

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2022-01-03
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多