log() function of logger class in Python with Example

The log() function of Python logger class records a message of specified severity into the logger object. If no handler object is specified the log is written to stderr.

Logger Updated 25 Mar 2017 1 min read

Method Name

log

Method Signature

critical(logLevel, logMessage, *args, **kwargs)

Method Overview

  • log() method records a message of specified log level to the logger object.

  • Logger object based on the handler attached to them outputs the log message in a specified destination.

  • Unless any specific handler is configured, the handler attached by default is stderr, which is generally the console.

  • The optional arguments to log() method *args, **kwargs enrich the log message with process name, line number of the module, information about the exception and stack and so on.

  • These optional arguments are explained in detail as part of the debug() method of the logger class.

Example

python
import logging

# Get a logger with the name of the current module

loggerObject    = logging.getLogger(__name__)

logFormat       = '%(asctime)s %(filename)s %(processName)s---%(message)s'

logging.basicConfig(level=logging.DEBUG, format=logFormat)

# Try all the log levels

loggerObject.log(logging.DEBUG, "This is a DEBUG message")

loggerObject.log(logging.INFO, "This is a INFO message")

loggerObject.log(logging.WARNING, "This is a WARNING message")

loggerObject.log(logging.ERROR, "This is a ERROR message")

loggerObject.log(logging.CRITICAL, "This is a CRITICAL message")

Output

Output
2017-03-25 15:13:17,261 logr6.py MainProcess---This is a DEBUG message

2017-03-25 15:13:17,261 logr6.py MainProcess---This is a INFO message

2017-03-25 15:13:17,261 logr6.py MainProcess---This is a WARNING message

2017-03-25 15:13:17,261 logr6.py MainProcess---This is a ERROR message

2017-03-25 15:13:17,261 logr6.py MainProcess---This is a CRITICAL message