Вход в Python ничего не выводит - PullRequest
52 голосов
/ 10 августа 2011

В скрипте Python, который я пишу, я пытаюсь регистрировать события, используя модуль регистрации.У меня есть следующий код для настройки моего регистратора:

ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s"
DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"
LOG_CONFIG = {'version':1,
              'formatters':{'error':{'format':ERROR_FORMAT},
                            'debug':{'format':DEBUG_FORMAT}},
              'handlers':{'console':{'class':'logging.StreamHandler',
                                     'formatter':'debug',
                                     'level':logging.DEBUG},
                          'file':{'class':'logging.FileHandler',
                                  'filename':'/usr/local/logs/DatabaseUpdate.log',
                                  'formatter':'error',
                                  'level':logging.ERROR}},
              'root':{'handlers':('console', 'file')}}
logging.config.dictConfig(LOG_CONFIG)

Когда я пытаюсь запустить logging.debug("Some string"), я не получаю вывод на консоль, хотя эта страница в документации говоритчто logging.debug должен иметь корневой логгер, выводящий сообщение.Почему моя программа ничего не выводит и как я могу это исправить?

Ответы [ 3 ]

73 голосов
/ 10 августа 2011

Уровень регистрации по умолчанию - предупреждение.Так как вы не изменили уровень, уровень корневого регистратора все еще является предупреждением.Это означает, что он будет игнорировать все журналы с уровнем ниже, чем предупреждение, включая журналы отладки.

Это объясняется в руководстве :

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
* 1007Строка 'info' ничего не печатает, потому что уровень выше, чем info.

Чтобы изменить уровень, просто установите его в корневом логгере:

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

Другими словами,недостаточно определить обработчик с помощью level = DEBUG, фактический уровень ведения журнала также должен быть DEBUG, чтобы заставить его что-либо выводить.

4 голосов
/ 14 августа 2018

Может быть попробовать это?Кажется, проблема решена после удаления всех обработчиков в моем случае.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)
3 голосов
/ 15 мая 2019

Много лет спустя, похоже, все еще существует проблема с удобством использования Python logger. Вот некоторые пояснения с примерами:

import logging
# This sets the root logger to write to stdout (your console)
logging.basicConfig()

# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)

# The following line sets the root logger level as well:
logging.basicConfig(level=logging.NOTSET)


# You can either share the `logger` object between all your files or the
# handle `my-app`. The result is the same.
logger = logging.getLogger("my-app")

logger.info("this will get printed")

# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")

# If you wish to control the logging levels, you can set the level anywhere in the
# hierarchy:
#
# - root
#   - my-app
#     - component-a
#

# Example for development:
logger.setLevel(logging.DEBUG)

# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)


# For production you rather want:
logger.setLeve(logging.WARNING)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...