How to use python logging for a single package
Asked Answered
T

1

6

I am developing a package and using logging module for my debug/info logs during development. Is there a good way to enable logging for just my package without enabling it for everything below root?

Say I have my_package:

# Some package from elsewhere that I need but don't want to see logging from
import other_package  
    
import logging
from logging import NullHandler
logger = logging.getLogger(__name__)
logger.addHandler(NullHandler())

def my_func():
    logger.debug("a message")

and a main function to use the package:

import my_package
    
# Some package from elsewhere that I need but don't want to see logging from
import another_package

import logging
logging.basicConfig(level=logging.DEBUG)

my_package.my_func()

This setup will let me see my_func()'s call to logger.debug(), but it will also show any logger.debug() calls from other_package and another_package, which I don't want to see. How can I set things where I only see the logging from my_package?

I could do hacky things like hard-code disable each other package's logging.propagate or similar, but that feels like there should be a better way.

Turoff answered 10/6, 2019 at 19:1 Comment(0)
A
4

You've already defined a unique logger for your package. You just need to configure that. Since the package logger inherits from the root logger, anything you specify with basicConfig applies to it as well. You just need to perform logger-specific overrides after you call basicConfig.

import logging
logging.basicConfig(level=logging.WARNING)
logging.getLogger('my.package').setLevel(logging.DEBUG)
Agog answered 10/6, 2019 at 19:15 Comment(1)
damn you're right. I thought I tried this and it wasn't working, but I must have messed something up the first time. Maybe I initialized the logging after importing other things before? Not sure what... anyway this is working for me. Thanks!Turoff

© 2022 - 2024 — McMap. All rights reserved.