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.handler = logging.FileHandler('path_to_logs_directory' + os.sep + 'logs' + os.sep + 'dark.log')
		self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
	def info(self, message):
	def debug(self, message):
	def warning(self, message):
	def error(self, message):
	def critical(self, message):
Categories: Python Tags: , ,
%d bloggers like this: