logger class

The logger class in Python implements the logging methods for most common severity levels used by developers. Logger objects can be given a name as well.

Logger Updated 24 Mar 2017 1 min read

Overview

  • The Logger class in Python implements logging functions, which can be used by Python Developers.

  • There are methods in Logger class for most common severity levels of log entries used by developers. They are

    • debug()
    • info()
    • warning()
    • error()
    • critical()
  • The logger class can be instantiated using the getlogger() method of logging module.

  • Python using names given by developers maintains the logger instances.

  • When no name is passed to the getlogger()method, a logger object with name root is returned.

  • Though any meaningful name can be passed inside the getlogger()method, the recommended way is to pass the current module name by calling getLogger() with the parameter __name__. This will create loggers with the Python package hierarchy and the module name.

  • To set the log level the logging.basicConfig method to be used passing the log level constants defined.

  • The log levels defined in Python are given in the below table:

Log levelNumeric value
NOTSET0
DEBUG10
INFO20
WARNING30
ERROR40
CRITICAL50

Example – Logging using logger class in Python

python
import logging

# Set log level to DEBUG

logging.basicConfig(level=logging.DEBUG)

logr = logging.getLogger(__name__)

# All the messages will be logged as log level is DEBUG

logr.debug("Debug Msg")

logr.info("Info Msg")

logr.warning("Warning Msg")

logr.error("Error Msg")

logr.critical("Critical Msg")

Output – Sample log printed to stderr – i.e., Console

Output
DEBUG:__main__:Debug Msg

INFO:__main__:Info Msg

WARNING:__main__:Warning Msg

ERROR:__main__:Error Msg

CRITICAL:__main__:Critical Msg