Topics

Python Logging in a file

Welcome to a tutorial, on Print Logs in a File in Python. 

Suppose, if we decide to print python logs in a file, instead on the console, we can do that by using the basicConfig() method by Providing filename and filemode as a parameter.

Also, by using the format parameter in basicConfig() method the format of the message can be specified.

Check out the example below to print logs to a file instead of the console.

import logging    # first of all import the module

logging.basicConfig(filename='std.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This message will get logged on to a file')

Output:

root - ERROR - This message will get logged on to a file

 

From the example above, the output displays what the message will look like, however, know that it will be written to a file name std.log rather than the console.

Also, the filemode is set to w, meaning that the log file is opened in “write mode” each time the basicConfig() is called, then after every run of the program, it will rewrite the file. However, the default configuration for filemode is a that is append, meaning that the logs will be appended to the log file and adding logs to the present logs.

 

Python Logging - Store Logs in a File

Below are the basics to store logs in a file.

Step 1: Import the logging module by writing import logging.

Step 2: Create and configure the logger. For you to configure logger to store logs in a file, it is mandatory to pass the name of the file in which you want to record the events.

Step 3: in this step, the format of the logger can also be set. Take note that by default, the file works in append mode, however, you can change that to write mode if required.

Step 4: Finally, you can set the level of the logger.

 

Example

Check out the example below:

#importing the module 
import logging 

#now we will Create and configure logger 
logging.basicConfig(filename="std.log", 
					format='%(asctime)s %(message)s', 
					filemode='w') 

#Let us Create an object 
logger=logging.getLogger() 

#Now we are going to Set the threshold of logger to DEBUG 
logger.setLevel(logging.DEBUG) 

#some messages to test
logger.debug("This is just a harmless debug message") 
logger.info("This is just an information for you") 
logger.warning("OOPS!!!Its a Warning") 
logger.error("Have you try to divide a number by zero") 
logger.critical("The Internet is not working....")

Output:

2022-08-11 07:44:00,449 - This is just harmless debug message
2022-08-11 07:44:00,449 - This is just an information for you
2022-08-11 07:44:00,449 - OOPS!!!Its a Warning
2022-08-11 07:44:00,449 - Have you try to divide a number by zero
2022-08-11 07:44:00,449 - The Internet is not working...

In addition, we can change the format of logs, log level, or any other attribute of the LogRecord along with setting the filename to store logs in a file along with the mode.