Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the default format of log messages in python app engine?

I would like to log the module and classname by default in log messages from my request handlers.

The usual way to do this seems to be to set a custom format string by calling logging.basicConfig, but this can only be called once and has already been called by the time my code runs.

Another method is to create a new log Handler which can be passed a new log Formatter, but this doesn't seem right as I want to use the existing log handler that App Engine has installed.

What is the right way to have extra information added to all log messages in python App Engine, but otherwise use the existing log format and sink?

like image 982
dazed-n-confused Avatar asked Mar 31 '10 23:03

dazed-n-confused


People also ask

What is the default log in Python?

So far, we have seen the default logger named root , which is used by the logging module whenever its functions are called directly like this: logging. debug() . You can (and should) define your own logger by creating an object of the Logger class, especially if your application has multiple modules.

What is the default for format in Python?

style defaults to "%" if not present in the basicConfig method. This gives us the format _STYLE["%"][1] = BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s".

What is Python logging StreamHandler?

StreamHandler. The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).


2 Answers

I cooked this up by reading the logging module's __init__.py. I don't know if this is proper, but it seems to work:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    )

logging.info('Danger Will Robinson!')
# 03-31 20:00 root         INFO     Danger Will Robinson!
root = logging.getLogger()
hdlr = root.handlers[0]
fmt = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
hdlr.setFormatter(fmt)
logging.info('Danger Will Robinson!')
# root        : INFO     Danger Will Robinson!
like image 140
unutbu Avatar answered Sep 19 '22 06:09

unutbu


I found this to be working for Python 3.6, it will set the logging level / format for all subsequent logging calls, even if logging is called by previous imports.

logging_level = logging.INFO
logging_fmt = "%(levelname)s:%(name)s:%(message)s"   # the default
try:
    root_logger = logging.getLogger()
    root_logger.setLevel(logging_level)
    root_handler = root_logger.handlers[0]
    root_handler.setFormatter(logging.Formatter(logging_fmt))
except IndexError:
    logging.basicConfig(level=logging_level, format=logging_fmt)
like image 45
Jia Huei Avatar answered Sep 21 '22 06:09

Jia Huei