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.
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.
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.
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.
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With