Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python using basicConfig method to log to console and file

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.

like image 901
Jovik Avatar asked Nov 20 '12 18:11

Jovik


People also ask

What is logging basicConfig in Python?

Python logging basicConfig The basicConfig configures the root logger. It does basic configuration for the logging system by creating a stream handler with a default formatter. The debug , info , warning , error and critical call basicConfig automatically if no handlers are defined for the root logger.

How do I log into the console in Python?

Use the logging Module to Print the Log Message to Console in Python. To use logging and set up the basic configuration, we use logging. basicConfig() . Then instead of print() , we call logging.

How do I print a log file in Python?

Python - Print Logs in a File. If you want to print python logs in a file rather than on the console then we can do so using the basicConfig() method by providing filename and filemode as parameter. The format of the message can be specified by using format parameter in basicConfig() method.


1 Answers

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__) 
like image 91
kartheek Avatar answered Oct 14 '22 00:10

kartheek