简体   繁体   English

python日志被抑制

[英]python logs get suppressed

My tornado application is using some legacy modules written many years back. 我的龙卷风应用程序使用的是许多年前编写的遗留模块。 Those modules are configured to log out things with root logger. 这些模块配置为使用root logger登出内容。 The issue I am facing is that whenever I import those modules the logs printed by the tornado(ie tornado.access, tornado.application, etc..) get suppressed. 我面临的问题是,每当导入这些模块时,龙卷风打印的日志(即tornado.access,tornado.application等)都会被抑制。

Here is how I invoke my server 这是我调用服务器的方式

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Basic run script"""

from zmq.eventloop import ioloop
ioloop.install()

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.autoreload
from tornado.options import options
import tornado.web

from grace_server.application import MyApplication
from settings import settings

def main():
    app = MyApplication(settings)
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()

Here is the definition of the tornado.Application 这是tornado.Application的定义。

import collections, zmq, os
import logging, re
import pickle, json
from datetime import datetime
from functools import partial

from zmq.eventloop.zmqstream import ZMQStream
from zmq.eventloop import ioloop

from tornado import web
from tornado.log import LogFormatter, app_log, access_log, gen_log
from jupyter_client import MultiKernelManager

from legacy_module import api
from legacy_module.util.utils import get_env

from urls import url_patterns


ioloop = ioloop.IOLoop.current()

class MyApplication(web.Application):

    def __init__(self, settings):
        self.init_logging()
        self.connections = collections.defaultdict(list)
        self.kernels = {}
        self.listen_logs()
        web.Application.__init__(self, url_patterns, **settings)


    def init_logging(self):
        self.logger = logging.getLogger('MyApplication')
        self.logger.setLevel(logging.DEBUG)


    def broadcast_message(self, message):
        connections = self.connections.keys()
        for conn in connections:
            conn.write_message(message)

    def multicat_message(self, filter_, message):
        connections = self.connections.keys()
        connections = filter(connections)
        for conn in connections:
            conn.write_message(message)

    ...
    ...
    ...

This is how logging is configured in my legacy_module 这是在我的legacy_module配置logging方式

import os, json
import logging, logging.config
from contextlib import contextmanager

from kombu import Connection
from terminaltables import AsciiTable

from legacy_module import resources
from legacy_module.resources.gredis import redis_tools
from legacy_module.core import versioning
from legacy_module.util.utils import get_logger_container, get_env

from legacy_module.resources.databases.mongo import MongoDatabaseCollection

DB_COLLECTION_OBJECT = MongoDatabaseCollection()

LOGGING_FILE = os.path.join(os.environ['legacy_module_HOME'], 'config', 'logging.config')
logging.config.fileConfig(LOGGING_FILE)
LOGGER = logging.getLogger()

...
...
...

This is how logging.config looks. 这就是logging.config外观。

[loggers]
keys = root

[handlers]
keys = consoleHandler

[formatters]
keys = simpleFormatter

[logger_root]
level = DEBUG
handlers = consoleHandler

[handler_consoleHandler]
class = StreamHandler
level = DEBUG
formatter = simpleFormatter
args = (sys.stdout,)

[formatter_simpleFormatter]
format = %(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt = 

This is how normal logs looks like 这是普通日志的样子

2017-09-28 02:40:03,409 MyApplication DEBUG    init_logging done
2017-09-28 02:40:13,018 MyApplication DEBUG    Authenticating

But When I comment out the import for legacy_module from MyApplication , I can see tornado.access logs 但是,当我注释掉MyApplicationlegacy_module的导入时,我可以看到tornado.access日志

2017-09-28 02:40:03,409 MyApplication DEBUG    init_logging done
2017-09-28 02:40:13,017 tornado.access INFO     304 GET / (172.20.20.3) 1.79ms
2017-09-28 02:40:14,264 tornado.access INFO     304 GET /api/login (172.20.20.3) 0.75ms
2017-09-28 02:40:13,018 MyApplication DEBUG    Authenticating

so the logging configurations of my legacy_module is some how suppressing the logs by the tornado . 所以我的legacy_modulelogging配置是如何通过tornado抑制日志的。 How can I fix this, I need these logs. 如何解决此问题,我需要这些日志。

First, in yourlegacymodule, remove the logging.config.fileConfig(LOGGING_FILE) call and replace LOGGER = logging.getLogger() with LOGGER = logging.getLogger(__name__) . 首先,在您的旧版模块中,删除logging.config.fileConfig(LOGGING_FILE)调用,并将LOGGER = logging.getLogger()替换为LOGGER = logging.getLogger(__name__)

Then you may want to make sure you have at least the root logger properly configured (don't know what you get in tornado for logging config so check the docs). 然后,您可能要确保至少已正确配置了根记录器(不知道在龙卷风中获取什么用于记录配置,因此请检查文档)。

As a more general note: this logging configuration in a library module is the perfect example of logging antipattern - the whole point of the logging package is to decouple logger's use (from within library code) from logging config which should be left to the application using the library code and should be configurable per application instance . 作为更一般的注释:库模块中的此日志记录配置是记录反模式的完美示例- logging包的全部要点是将记录器的使用(从库代码中)与日志记录配置分开,应使用库代码,应该每个应用实例都可配置。 FWIW note that your own MyApplication.init_logging() is also an antipattern - you shouldn't hardcode the logger's level in your code, this should be done using a per-instance config (cf how django uses the settings module to configure logging). FWIW注意,您自己的MyApplication.init_logging()也是一种反模式-您不应在代码中对记录器的级别进行硬编码,而应使用每个实例的配置来完成(参见django如何使用settings模块配置日志记录)。

Update: 更新:

I'd have to dig into tornado's code to give you an exact detailed answer, but obviously the logging.config.fileConfig() call in yourlegacymodule overrides tornado's own configuration. 我必须深入研究龙卷风的代码才能为您提供确切的详细答案,但是显然,您的旧模块中的logging.config.fileConfig()调用会覆盖龙卷风自己的配置。

are my configs done in init_logging get overridden by the root logger ? 我在init_logging中完成的配置是否被root记录程序覆盖?

The only thing you currently "configure" (and which you shouldn't) in init_logging is the "MyApplication" logger's level, this has no impact on which loggin handler is used (=> where your logs are sent) etc. 当前在init_logging唯一“配置”(并且不应配置)的唯一东西是“ MyApplication”记录器的级别,这对使用哪个loggin处理程序(=>发送日志的位置)没有影响。

how can I prevent them ? 我该如何预防?

This was the very first part of my answer... 这是我回答的第一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM