Changing logging level only for my code?

Peter Otten __peter__ at web.de
Mon Feb 8 07:12:28 EST 2016


egarrulo at gmail.com wrote:

> I am using the "logging" module for my own package, but changing the level
> from "INFO" to "DEBUG" enables debugging statements from third-party
> libraries as well.  How can I avoid them?  Here is the code I am using:
> 
>     import logging
> 
>     logger = logging.getLogger(__name__)
>     log_file = logging.FileHandler("activity.log", mode='w')
>     log_file.setFormatter(logging.Formatter(fmt='%(levelname)s:
>     %(message)s')) logger.addHandler(log_file)
>     logging.basicConfig(level=logging.INFO) # or DEBUG

You can set the level for your logger, e. g.

$ cat loglevels.py
import logging

logging.basicConfig(
    level=logging.INFO,
    filename="activity.log",
    format='%(levelname)s: %(message)s')

mylogger = logging.getLogger(__name__)
mylogger.setLevel(logging.DEBUG)

mylogger.info("my info")
mylogger.debug("my debug message")

otherlogger = logging.getLogger("some.lib")

otherlogger.info("some.lib info")
otherlogger.debug("some.lib debug message")

$ python3 loglevels.py 
$ cat activity.log 
INFO: my info
DEBUG: my debug message
INFO: some.lib info





More information about the Python-list mailing list