Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can python log output without INFO:root

Tags:

python

logging

I use the Python logging framework with default settings. For some data compare reason:I have to compare the log with other data output. But the python log begin with a default, something like:

INFO:root:post params in transmitter

Can I set the python log output without INFO:root:, like:

post params in transmitter

with my own log only?

Thx a lot!

like image 266
littletiger Avatar asked Dec 02 '11 08:12

littletiger


2 Answers

Sure thing. You could set the format to watever you like:

format: '%(message)s'

Like this:

logging.basicConfig(format='%(message)s', ...)

See the doc for more info: http://docs.python.org/library/logging.config.html

like image 85
UlfR Avatar answered Oct 31 '22 04:10

UlfR


Those "INFO:..." or "DEBUG:..." appear there because some handler defines that. My guess: the default handler is still there.

You can check it by taking a peek at logger.handlers right after you created it.

logger = logging.getLogger()
logger.handlers = [] # This is the key thing for the question!

# Start defining and assigning your handlers here
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

Also, you could just override the format for that default handler:

if (len(logger.handlers) > 0): # Check here whatever. Or try/except. You get the idea...
    formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
    logger.handlers[0].setFormatter(formatter)

I am not a Python expert so maybe there is a better way to remove or even not create that default handler but this works pretty well for me.

Note: As stated in the docs, the .basicConfig is useful for simple loggers. If you have multiple streams, with multiple formats, it does not work as far as I know and you need to go with the custom handlers.

like image 27
Dani bISHOP Avatar answered Oct 31 '22 04:10

Dani bISHOP