In Python, you can use the built-in logging
module to print logging in a file. Here are the basic steps to do this:
logging
module:import logging
logging.FileHandler
object, and specify the file name and mode in which the file should be opened:file_handler = logging.FileHandler('example.log', mode='w')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(file_handler)
logging
methods to print the logs in the file:logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
This code will create a file named example.log
in the current working directory and write the logs in it. Each log message will include the date and time, the logger name, the level of the message, and the message itself.
It’s important to note that when you are done with the logging, you should close the file handler by calling file_handler.close()
You can also use other options to customize the logging, like rotating the file when it reaches a certain size or creating a new file when the log reaches a certain date.
#importing the module
import logging
#now we will Create and configure logger
logging.basicConfig(filename="File1.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("debug message")
logger.info("information")
logger.warning("Warning")
logger.error("error")
logger.critical("critical")
The above code will write some messages to a file named File1.log.
Note: also read about Logging basicConfig()function
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…