Python using basicConfig method to log to console and file

Jovik picture Jovik · Nov 20, 2012 · Viewed 76.4k times · Source

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 (example code), 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

Answer

kartheek picture kartheek · May 15, 2014

Try this working fine(tested in python 2.7) for both console and file

# set up logging to file
logging.basicConfig(
     filename='log_file_name.log',
     level=logging.INFO, 
     format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
     datefmt='%H:%M:%S'
 )

# set up logging to console
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

logger = logging.getLogger(__name__)