Python Logging Module
The logging module lets you record debug, info, warning, error, and exception messages in a consistent way.
import logging
Use logging instead of print() when messages have different importance levels or when you may later send them to a file.
Basic configuration
basicConfig configures the default logger.
import logging
logging.basicConfig(level=logging.INFO)
logging.info('Application started')
logging.warning('Low disk space')
INFO:root:Application started
WARNING:root:Low disk space
Messages below the configured level are ignored:
import logging
logging.basicConfig(level=logging.WARNING)
logging.info('Hidden message')
logging.warning('Visible message')
WARNING:root:Visible message
Creating a named logger
Named loggers are useful in larger applications.
import logging
logger = logging.getLogger('app.users')
logger.setLevel(logging.INFO)
print(logger.name)
app.users
Formatting messages
You can customize the output format.
import logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(message)s',
)
logger = logging.getLogger('app')
logger.info('Ready')
INFO:app:Ready
Logging exceptions
logger.exception records the traceback automatically inside an except block.
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
try:
1 / 0
except ZeroDivisionError:
logger.exception('Calculation failed')
ERROR:__main__:Calculation failed
Traceback (most recent call last):
...
ZeroDivisionError: division by zero