Logging is used to track events that occur while the software is running. Using logging, you can add logging calls in your code to indicate that certain events have occurred. This way you can learn about errors, messages, warnings, and more.
For logging, different functions are provided. You must decide when to use logging. For this purpose, Python provides the following:
ogging.info() - Reports events that occur during normal operation of the program.
logging.warning() - Issue a warning about a specific runtime event.
logging.error() − Report error suppression without raising an exception.
The standard severity levels for events are as follows, in order of increasing severity. These levels include DEBUG, INFO, WARNING, ERROR, CRITICAL −
DEBUG − This is detailed information that is usually only of interest when diagnosing a problem.
INFO − Used when confirming that something is working perfectly.
Warning - This is the default level. It indicates that something unexpected happened or indicates that there will be problems in the future, such as insufficient memory, insufficient disk space, etc.
Error - The software is unable to perform certain functions due to a more serious problem.
CRITICAL − A critical error indicating that the program itself may not be able to continue running.
Let’s look at a simple example -
import logging # Prints a message to the console logging.warning('Watch out!')
WARNING:root:Watch out!
As mentioned above, warning is the default level. If you try to print other levels, it won't be printed -
import logging # Prints a message to the console logging.warning('Watch out!') # This won't get printed logging.info('Just for demo!')
WARNING:root:Watch out!
To log variable data, you need to use the format string of the event description message and append the variable data as a parameter.
import logging logging.warning('%s before you %s', 'Look', 'leap!')
WARNING:root:Look before you leap!
When we talk about logging, the key is to include the date/time of the event. This is mainly to record when warnings or errors occur −
import logging logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('is the Log Time.')
2022-09-19 17:42:47,365 is the Log Time.
The above is the detailed content of Python Logging Basics - A Simple Guide. For more information, please follow other related articles on the PHP Chinese website!