Logging is an essential part of any program to track its execution, report errors, and store other relevant information. The logging
module is used to log messages.
You can log messages using different levels: DEBUG
, INFO
, WARNING
, ERROR
, and CRITICAL
.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
This code sets up logging and logs messages of various severity levels.
You can also log messages to a file:
logging.basicConfig(filename='app.log', level=logging.DEBUG)
logging.info("Logging to a file now.")
By setting filename
, the log messages will be written to a file instead of the console.
Set up logging for an application that logs user login attempts with timestamps.
Answers: The default logging level is WARNING
. You can log messages to a file by setting the filename
parameter in basicConfig()
.