Pablo
Pablo

Reputation: 11031

Enforce no-root-logger policy for Python

I work on an open source project, and in the project we used to allow all modules to log on the root logger:

import logging


def my_function():
  logging.info('Logging something on the root- logger')

We're moving to use per-module loggers, like so:

import logging

_LOGGER = logging.getLogger(__name__)


def my_function():
  _LOGGER.info('Logging something on the root- logger')

Is there a way to enforce this policy via Linter / Static checks, so that others will not log on the root logger?

Upvotes: 1

Views: 58

Answers (1)

blues
blues

Reputation: 5185

That is definitely not possible with static checking if you want to find all cases where that happens. The best you can achieve is basically looking for the string logging.[info|debug|...] in the source. A static checker is easily fooled by something like this:

logger_name = 'root' # might even read this from a config file
_LOGGER = logging.getLogger(logger_name) # static check has no way to know here that we get the root logger 
_LOGGER.info('logging this to root')

Besides that, if you don't set propagate to false on your module level loggers they still propagate their logs to the root logger.

Upvotes: 2

Related Questions