Setting the logging level for the logger object will allow all messages at and above that level to be produced in the output stream. The logging level can be set by using setLevel()
. If no level is manually set, the default level logging.WARNING
is used.
import logginglogger.setLevel(logging.INFO)
Formatting of logged messages can be changed by using the Formatter
class. Information like timestamps, function names, and line numbers can be included in the logged message.
import loggingformatter = logging.Formatter('[%(asctime)s] %(message)s')
Log messages can be directed to both files and the console by adding FileHandler
and StreamHandler
handler objects to the logger.
While logging to console is helpful if needing to review debugging log messages in real-time, logging to a file allows for the logged messages to exist well after the program execution has occurred.
import loggingimport sysfile_handler = logging.FileHandler("program.log")stream_handler = logging.StreamHandler(sys.stdout)
For a simple, one-liner configuration of the logger, there is a basicConfig()
method that will allow for adding handlers, setting formatting options for the logged messages, and setting the log level for the logger.
import logginglogging.basicConfig(filename='program.log', level=logging.DEBUG, format= '[%(asctime)s] %(levelname)s - %(message)s')
Logging messages and exceptions is important for debugging applications and for logging important information that generates during execution. The proper method for logging these messages is the logging
module.
import logging
There are six logging levels associated with the logging module:
import logginglogging.DEBUGlogging.INFOlogging.WARNINGlogging.ERRORlogging.CRITICALlogging.NOTSET