Skip to content Skip to sidebar Skip to footer

Filehandler Not Sending Output To Either Location I Want

First time playing around with the logging module. I have two questions really: All of the examples I have found on creating a FileHandler just use a dummy file name, but I want my

Solution 1:

Your code is configuring a logger named 'myproject':

logger = logging.getLogger('myproject')
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

If you use methods on that logger, everything will work:

logger.info('foo bar')
logging.getLogger('myproject').info('foo bar')

But if you just use the module-level functions, it will not:

logging.info('foo bar')

Why? Because the module-level functions use the default root logger, which is not the one you've configured. See the docs for details on how this works.

Generally, the way you deal with this is either to create a module-level logger object for each module, like this:

logger = logging.getLogger(__name__)

… or a class or instance attribute logger, something like this:

self.logger = logging.getLogger('{}.{}'.format(__name__, cls.__name__))

And then do everything through that logger or self.logger object, not through the module-level functions.

So, why are the module-level functions even there? For convenience in simple programs, mainly. If that sounds appropriate for you, and you want to use them, you can; you just have to configure the root logger instead of a different one. Change the first line to this:

logger = logging.getLogger()

Now when you configure logger, you're also configuring the module-level functions.

Post a Comment for "Filehandler Not Sending Output To Either Location I Want"