Logging in Python

Logging module defines functions and classes which implement a flexible event logging system for applications and libraries.

The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.

The module provides a lot of functionality and flexibility. The basic classes defined by the module, together with their functions, are listed below.

– Loggers expose the interface that application code directly uses.
– Handlers send the log records (created by loggers) to the appropriate destination.
– Filters provide a finer grained facility for determining which log records to output.
– Formatters specify the layout of log records in the final output.

Let’s see a simple logger class which logs errors to file:

import logging, os
 
class MyLogger():
 
	def __init__(self, logger_name):
		self.logger = logging.getLogger(logger_name)
		self.logger.setLevel(logging.INFO)
		self.handler = logging.FileHandler('path_to_logs_directory' + os.sep + 'logs' + os.sep + 'dark.log')
		self.handler.setLevel(logging.INFO)
		self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
		self.handler.setFormatter(self.formatter)
		self.logger.addHandler(self.handler)
 
	def info(self, message):
		self.logger.info(message)
 
	def debug(self, message):
		self.logger.debug(message)
 
	def warning(self, message):
		self.logger.warning(message)
 
	def error(self, message):
		self.logger.error(message)
 
	def critical(self, message):
		self.logger.critical(message)
Categories: Python Tags: , ,
%d bloggers like this: