Set logging levels

I am trying to use the standard library to debug my code:

This works great:

import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('message') 

I can not get the logger to work for the lower levels:

 logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('message') logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.debug('message') 

I get no answer for any of them.

+25
source share
2 answers

What version of Python? This worked for me in 3.4. But note that basicConfig () will not affect the root handler if it is already configured:

This function does nothing if handlers are already configured for the root logger.

To explicitly set the level for root, do logging.getLogger().setLevel(logging.DEBUG) . But make sure you basicConfig() so that the root logger has some settings. I.e:

 import logging logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('foo').debug('bah') logging.getLogger().setLevel(logging.INFO) logging.getLogger('foo').debug('bah') 

Also note that "Loggers" and their "Handlers" have different independent log levels. So if you previously explicitly loaded some complex logger configuration in your Python script, and it messed up with the root logger's handler (s), this can have an effect, and just logging.getLogger().setLevel(..) level of logging.getLogger().setLevel(..) using logging.getLogger().setLevel(..) may not work. This is because the log level can be independently set for the connected handler. This is hardly the case, and you have nothing to worry about.

+35
source

I use the following setting for logging

Yaml based configuration

Create a yaml file called logging.yml , like this

 version: 1 formatters: simple: format: "%(name)s - %(lineno)d - %(message)s" complex: format: "%(asctime)s - %(name)s - %(lineno)d - %(message)s" handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple file: class: logging.handlers.TimedRotatingFileHandler when: midnight backupCount: 5 level: DEBUG formatter: simple filename : Thrift.log loggers: qsoWidget: level: INFO handlers: [console,file] propagate: yes __main__: level: DEBUG handlers: [console] propagate: yes 

Python is the main

The "core" module should look like this:

 import logging.config import logging with open('logging.yaml','rt') as f: config=yaml.safe_load(f.read()) f.close() logging.config.dictConfig(config) logger=logging.getLogger(__name__) logger.info("Contest is starting") 

Submodules / Classes

They should start as follows

 import logging class locator(object): def __init__(self): self.logger = logging.getLogger(__name__) self.logger.debug('{} initialized') 

Hope this helps you ...

+6
source

All Articles