Making Python loggers out all messages to stdout addition to log

Czy istnieje sposób, aby logowanie Pythona za pomocą modułu logging automatycznie wysyłało rzeczy do stdout dodatkowo do pliku dziennika, gdzie mają się udać? Na przykład, chciałbym, aby wszystkie połączenia do logger.warning, logger.critical, logger.error aby przejść do ich zamierzonych miejsc, ale w dodatku zawsze być kopiowane do stdout. Ma to na celu uniknięcie powielania wiadomości typu:

mylogger.critical("something failed")
print "something failed"
Author: Martijn Pieters, 2012-12-27

5 answers

Wszystkie wyjścia logowania są obsługiwane przez programy obsługi; wystarczy dodać logging.StreamHandler() do głównego rejestratora.

Oto przykład konfigurowania obsługi strumienia (używając stdout zamiast domyślnego stderr) i dodania go do głównego rejestratora:

import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
 435
Author: Martijn Pieters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-07 10:13:25

Najprostszy sposób:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
 337
Author: Eyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-18 03:56:17

Jest to możliwe przy użyciu wielu programów obsługi.

import logging
import auxiliary_module

# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)

log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')

log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')

log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')

# remember to close the handlers
for handler in log.handlers:
    handler.close()
    log.removeFilter(handler)

Zobacz: https://docs.python.org/2/howto/logging-cookbook.html

 46
Author: Alok Singh Mahor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-05 13:03:21

Najprostszy sposób logowania do pliku i do stderr:

  import logging
  logging.basicConfig(filename="logfile.txt")
  stderrLogger=logging.StreamHandler()
  stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
  logging.getLogger().addHandler(stderrLogger)
 28
Author: Weidenrinde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-22 08:25:00

Można utworzyć dwa programy obsługi dla file i stdout, a następnie utworzyć jeden logger z argumentem handlers do basicConfig. Może to być użyteczne, jeśli masz taki sam log_level i format dla obu programów obsługi:

import logging
import sys

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG, 
    format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
    handlers=handlers
)

logger = logging.getLogger('LOGGER_NAME')
 24
Author: Anton Protopopov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-05 05:08:01