Python Logging Module

Python Logging Module

  • logging module provides a full featured and flexible event logging system for applications and libraries.
  • By default, log messages are directed to a file or to sys.stderr(standard error).
  • logging module is thread-safe and additional work is not needed.

Different logging levels based on priority

  • DEBUG - numeric level : 10
  • INFO - numeric level : 20
  • WARNING - numeric level : 30
  • ERROR - numeric level : 40
  • CRITICAL - numeric level : 50
By default, informational and debugging messages are suppressed and sent to standard error.

Output options to log messages

  • File
  • sys.stderr
  • Email
  • Datagrams
  • sockets
  • HTTP Server

Python Logging Example Scripts

import logging                                                                  
logging.debug('Debugging info');                                                
logging.info('Informational details');                                          
logging.warning('Warning message');                                             
logging.error('Error message');                                                 
logging.critical('Critical error');  
Output:
$ python logging_test.py 
WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical error

Logger Objects

  • Loggers are instantiated through the module-level function logging.getLogger(name).
  • Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.
  • Recommended construction
    logging.getLogger(__name__)
    
    here __name__ is the module’s name in python package namespace and this getLogger method returns class 'logging.Logger'.

Python program for logging using Logger Objects

import logging                                                                  
                                                                                
Log = logging.getLogger("test");                                                
                                                                                
class Arithmetic:                                                               
    def __init__(self, a, b):                                                   
        self.a = a;                                                             
        self.b = b;                                                             
                                                                                
    def div(self):                                                              
        # Log message can be added in any methods based on message priority.
        Log.debug('Debugging info');                                            
        Log.info('Informational details');                                      
        Log.warning('Warning message');                                         
        Log.error('Error message');                                             
        Log.critical('Critical error');  
                                       
        return self.a/self.b;                                                   
                                                                                
arth = Arithmetic(10, 2);                                                       
result = arth.div();                                                            
                                                                                
print(result);  
Output:
$ python3 logging_test.py 
Warning message
Error message
Critical error
5.0
need to use python3 interpreter, otherwise error will be printed like 'No handlers could be found for logger "test"' for python interpreter but result 5 also printed.

Logger Object Methods

  • debug method: Logs a DEBUG level message on current logger.
    Logger.debug(debug_message, *args, **kwargs)¶
    
    debug_message is the message format string, and the args are merged into debug_message using the string formatter or can also use keywords in the format string with a single dictionary argument.
  • info method: Logs a INFO level message on current logger.
    Logger.info(information_message)
    
    information_message can also be like debug_message formatter with arguments.
  • warning method: Logs a WARNING level message on current logger.
    Logger.warning()
    
  • error method: Logs a ERROR level message on current logger.
    Logger.error(error_message)
    
  • critical method: Logs a CRITICAL level message on current logger.
    Logger.critical(msg, *args, **kwargs)
    
  • log method: Logs a message with integer level lvl on this logger
    Logger.log(lvl, msg, *args, **kwargs)
    
  • exception method: Logs a ERROR level message on current logger. Exception details are always added to the logging message and this method should only be called from an exception handler.
    Logger.exception(msg, *args, **kwargs)
    

Handler Objects in python logging

Handler is never instantiated directly, Handler class can be used as base class for more subclasses. However, the __init__() method in subclasses needs to call like Handler.__init__().

Formatter Objects

Formatter Objects are responsible for converting a LogRecord to a string. Formatter allows a formatting string to be specified. default value of '%(message)s' is used if none is supplied, which just includes the message in the logging call.
format(record)
record is the dictionary and used as the operand to a string formatting operation. format method returns the string.

Filter Objects

Filters can be used by Handlers and Loggers for more sophisticated filtering than provided in default.
filter(record)
Returns nonzero if need to log specified records, returns zero if not needed to log specified records.

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^