Category: python
Introduction to Logging in Python
Published on 14 Aug 2026
Explanation
Logging is the process of recording events that happen while a Python application is running. Python provides a built-in logging module for creating application logs. Logging is more useful than print() statements in production applications because developers can control the log level, format, destination, and amount of information recorded. Logs are useful for debugging, monitoring application behavior, tracking errors, and investigating problems. Python provides five commonly used logging levels: DEBUG, INFO, WARNING, ERROR, and CRITICAL.
Code:
import logging
logging.basicConfig(level=logging.INFO)
logging.debug('Debug message')
logging.info('Application started')
logging.warning('This is a warning')
logging.error('An error occurred')
logging.critical('Critical error occurred')
Explanation
Python logging provides different levels to indicate the importance of an event. DEBUG is used for detailed information useful during development. INFO records normal application events. WARNING indicates a potential problem that does not stop the application. ERROR indicates that an operation failed. CRITICAL represents a serious error that may prevent the application from continuing. Setting an appropriate logging level allows applications to control which messages are displayed or stored.
Code:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('Debug: variable value checked')
logging.info('Info: user logged in')
logging.warning('Warning: disk space is low')
logging.error('Error: database connection failed')
logging.critical('Critical: application cannot continue')
Explanation
Logging messages can be customized using a format. A useful log format commonly includes the timestamp, logging level, logger name, and message. The %(asctime)s value represents the time when the log record was created, %(levelname)s represents the log level, and %(message)s contains the actual message. A consistent log format makes application logs easier to read, search, and analyze.
Code:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info('Application started')
logging.warning('User input is missing')
logging.error('Unable to process request')
Explanation
Logs can be written to a file instead of displaying them only on the console. This is useful for applications running on servers because developers can review the log file later to investigate errors and application behavior. The filename parameter specifies the log file, while filemode can control whether logs are appended or overwritten. In production applications, file-based logging is commonly combined with log rotation so that log files do not grow indefinitely.
Code:
import logging
logging.basicConfig(
filename='application.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info('Application started')
logging.info('User logged in')
logging.warning('Invalid login attempt')
logging.error('Database operation failed')
print('Logs written to application.log')
Explanation
Logging is especially useful when handling exceptions. The logging.exception() method records an error message along with the traceback when it is called inside an except block. This provides detailed information about where an error occurred, which makes debugging easier. In production applications, exception logging is commonly used for database errors, file processing errors, API failures, and unexpected runtime problems.
Code:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
try:
number = int(input('Enter a number: '))
result = 100 / number
print('Result:', result)
except ValueError:
logging.exception('Invalid number entered')
except ZeroDivisionError:
logging.exception('Cannot divide by zero')