Ivan
Ivan

Reputation: 64207

How to set logging level for the module only in Python?

I am using logging.info to output information about what my script is doing and I am using logging.basicConfig(level=logging.INFO) to enable this. And this (logging.basicConfig(level=logging.INFO)) also affects other modules I invoke (e.g. SQLAlchemy) causing a way much more verbose output than I want. Can I set the logging level to INFO for my actual script but not for the 3rd-party modules it uses (I'd prefer it to be WARNING for them)?

Upvotes: 4

Views: 8514

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

The normal way to do this is to define a logger for the current module - usually based on the file name - at the start of the module, and refer to this throughout.

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def function_that_logs():
    logger.info('will log')   # note, using logger not logging
    logger.debug('will not log')

Upvotes: 12

Related Questions