Python Logging Messages to Log File

Python – Logging Messages to Log File

Using Python Logging module, you can log debug lines, information, warnings, errors and critical errors to a log file instead of echoing to the console.

To log data to a file, using the logging basic configuration, set the filename with the location to the log file. If the file is not present, the Python system creates the file, provided it has permissions to create and write to a file in that location.

Syntax – Log to File

The syntax to set the filename using logging module’s basicConfig() function is shown below.

logging.basicConfig(filename="mylog.log")

You can change the file name to your choice.

Example 1: Logging Messages to Log File

In this example, we will set up the logging configuration using basicConfig() function, so as to log the messages to an external file named mylog.log. As complete path is not provided, this file will be created next to the working directory. Or you may provide the complete path to the log file.

Python Program

import logging

#setup logging basic configuration for logging to a file
logging.basicConfig(filename="mylog.log")

logging.warning('This is a WARNING message')
logging.error('This is an ERROR message')
logging.critical('This is a CRITICAL message')

Output

WARNING:root:This is a WARNING message
ERROR:root:This is an ERROR message
CRITICAL:root:This is a CRITICAL message

The logging appends messages to the file.

Example 2: Logging Messages to Log File using Handler

In this example, we will set up the logging configuration using basicConfig() function, so as to log the messages to an external file named mylog.log. As complete path is not provided, this file will be created next to the working directory. Or you may provide the complete path to the log file.

Python Program

import logging

#create a logger
logger = logging.getLogger('mylogger')

handler = logging.FileHandler('mylog.log')
logger.addHandler(handler)

logger.warning('This is a WARNING message')
logger.error('This is an ERROR message')
logger.critical('This is a CRITICAL message')

Output

This is a WARNING message
This is an ERROR message
This is a CRITICAL message

The logging appends messages to the file.

Summary

In this tutorial of Python Examples, we learned how to log messages to a file in persistent storage.