Python global logger

This article introduces logging, its various levels, and its importance in Python. Then, we'll learn how to use the Python logging module globally.


An Introduction to Logging and Its Importance in Python

Logging is a method of tracking events that occur while running software. Software developers add logging calls to record errors and events that occur when someone executes a program.

In Python programming, we have a built-in module called logging that records such errors and events. Note that events are messages and optionally save event-specific data.

These events can have different levels/severities, specified by the software developer. So, we can say that logging is a very powerful tool to debug our application and trace any needed information.

The logging module provides different ways for our application to configure various log handlers, route log messages to these handlers, and enable highly flexible configuration, which helps to handle various use cases.

The logging module also has different log levels to help us deal with various severity levels. Here is a brief description of the logging levels:

  • INFO - It confirms that various things are working as expected.
  • DEBUG - It provides typical details when someone is diagnosing a problem.
  • WARNING − It indicates that something happened unexpectedly. We can also say that WARNING indicates a problem that may occur soon, such as insufficient disk space.
  • CRITICAL - It indicates a critical error where the application itself cannot continue.
  • ERROR - It represents a more serious problem that does not allow the program to perform an operation or function.

Using the logging module globally in Python

We can use the logging module locally and globally in Python. Here, locally means to use the logging module in a specific scope; for example, we have introduced the logging module in A.py file, so we can only use it in A.py, not in B.py file.

On the other hand, global means used everywhere in A.py file and B.py file. Understanding the use of the native logging module is important to learning about the Python global logger.

Example code to use the logging module locally (saved in the test.py file):

import logging

logger = logging.getLogger("test_logger")
logger.setLevel(logging.INFO)

def sum_numbers(number1, number2):
    try:
        output = number1 + number2
    except TypeError:
        logger.exception("Oh! TypeError Occurred")
    else:
        return output

result = sum_numbers(10, 'Mehvish')

Here we use the logging module locally in the imported test.py file.

Then, we use getLogger()the logging module in Python to start logging. Execute the factory function for this logging.getLogger(name).

getLogger()Takes one argument, the name of the logger, and returns a reference to the logger instance (logger's object), using the name if specified, or the root otherwise.

Note that multiple calls to with the exact name getLogger()return a reference to the same logger instance, which is useful for using it globally (as we'll see later).

Next, we use setLevel()the method to set the level of logging, and write the sum_numbers() function, which takes two numbers of type int, adds them, and returns the result if the given value is correct; otherwise, it generates a TypeError .

Finally, we call to sum_numbers()see our logging module in action by producing the following results.

output:

Oh! TypeError Occurred
Traceback (most recent call last):
  File "E:\Code\use_logging_locally\test.py", line 8, in sum
    output = number1 + number2
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Using the logging module is easy, but how do you leverage this module globally? Let's learn below.

Sample code (saved in log.py file):

import logging

def set_custom_logger(name):
    formatter = logging.Formatter(
                    fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s'
                )

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    return logger

Sample code (saved in submodule.py file):

import logging

logger = logging.getLogger('root')
logger.debug('submodule message')

Sample code (saved in main.py file):

import log
logger = log.setup_custom_logger('root')
logger.debug('main message')

import submodule

output:

2022-10-27 09:31:02,447 - DEBUG - main - main message
2022-10-27 09:31:02,450 - DEBUG - submodule - submodule message

This code example prints the date, time, logging level, module name, and message.

请注意, we used in submodule.py logging.getLogger()to use the exact logger instance we used in the log.py file.

how? logging.getLogger(name)Typically run to start logging with the logging module in Python. getLogger() takes one argument, the name of the logger.

By using getLogger()the function, we can obtain a reference to a logger instance with a given name (if provided) or root directory (if not specified).

Calling multiple times with the exact name getLogger()returns a reference to the exact logger object, which helps us use it globally.

Guess you like

Origin blog.csdn.net/fengqianlang/article/details/131584747