如何使用记录器在特定日志文件中打印而不在龙卷风应用程序中的 supervisord 日志文件中打印

how to print in a specific log file using a logger without printing in the supervisord log file in a tornado application

我目前正在开发一个由不同独立模块组成的 Tornado 应用程序。

应用程序 运行 使用 supervisord,所以现在,每次我使用

logging.info()

日志打印在主管日志上,我同意。

问题是现在主管日志文件充满了来自不同模块的非常不同的东西并且很难阅读,所以我现在希望每个模块都使用特定的记录器并且每个记录器都写在不同的文件上。

所以我创建了记录器:

def set_log_config(filename, when='h', interval=1, backupCount=0):
    directory = os.path.dirname(os.path.abspath(filename))
    create_folder(directory)

    app_log = logging.getLogger("tornado.application.fiscal")

    handler = logging.handlers.TimedRotatingFileHandler(filename, when=when, interval=interval, backupCount=backupCount)
    formatter = logging.Formatter('[%(levelname)s %(asctime)s.%(msecs)d %(module)s:%(lineno)d] %(message)s', datefmt='%y%m%d %H:%M:%S')

    handler.setFormatter(formatter)
    app_log.addHandler(handler)
    app_log.setLevel(logging.INFO)
    return app_log

fiscal_logger = set_log_config(
        '/home/dir/Trace/fiscal/fiscal_module_{:%Y-%m-%d}.log'.format(datetime.now(), when='midnight', interval=1, backupCount=21)
    )

记录器工作,它写在特定文件上,但它也总是写在主管日志文件中,我不明白为什么。

所以我的问题是:当我使用 fiscal_logger.info 时如何在特定文件上写,而当我使用 logging.info 时如何在主管文件上写?

首先我解释一下为什么你的记录器也会写入主管日志文件。

写入主管日志文件意味着在您当前的记录器链中有一个 StreamHandler

logging.info 基本上等于 logging.getLogger().info 这意味着它使用 root 记录器。此外,如果 root 没有处理程序,logging.xxx 会自动将 StreamHandler 添加到 root 记录器。

并且默认情况下,日志将沿着记录器链传播(例如,"tornado.application.fiscal" 的记录器链是 root -> tornado -> application -> fiscal)。因此 fiscal_logger 的日志被传播到 root 记录器并由 rootStreamHandler 处理。这就是为什么您会在主管日志文件中看到这些日志的原因。


要解决这个问题,您至少有两个选择

  1. 不要再使用 logging.xxxx。相反,使用另一个命名记录器,例如 console_logger.
  2. fiscal_logger.propagate 设置为 False