Python using basicConfig method to log to console and file

console, file, logging, python, python-logging

Solution

I can't reproduce it on Python 3.3. The messages are written both to the screen and the `'example2.log'`. On Python <3.3 it creates the file but it is empty.

The code:

from logging_tree import printout  # pip install logging_tree
printout()

shows that `FileHandler()` is not attached to the root logger on Python <3.3.

The docs for `logging.basicConfig()` say that `handlers` argument is added in Python 3.3. The `handlers` argument isn't mentioned in Python 3.2 documentation.

Problem

I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there. ``` #!/usr/bin/env python3 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', handlers=[logging.FileHandler("example1.log"), logging.StreamHandler()]) logging.debug('This message should go to the log file and to the console') logging.info('So should this') logging.warning('And this, too') ``` I have "bypassed" this problem by creating a logging object, but it keeps bugging me why `basicConfig()` approach failed? PS. If I change basicConfig call to: ``` logging.basicConfig(level=logging.DEBUG, filename="example2.log", format='%(asctime)s %(message)s', handlers=[logging.StreamHandler()]) ``` then all logs are in the file and nothing is displayed in the console.

Original source