Aquesta és una revisió antiga del document —-

4.1 Logging in Python

The Python Standard Library provides a useful module called logging to log events occurring in the application. Logs are most often used to find the cause of an error. By default, Python and its modules provide many logs informing you of the causes of errors. However, it's good practice to create your own logs that may be useful to you or other programmers.

An example of using your own logs can be any Internet system. When users visit your site, you can log information about the browsers they use. If something goes wrong, you'll be able to determine in which browsers the problem is occurring.

In Python, you can store logs in different places. Most often it's in the form of a file, but it can also be an output stream, or even an external service. To start logging, we need to import the appropriate module:

import logging

In this part of the course, you'll learn how to create logs using the logging module. See what this module offers and start using it to become a better programmer.

One application may have several loggers created both by us and by programmers of the modules. If your application is simple, as in the example below, you can use the root logger. To do this, call the getLogger function without providing a name. The root logger is at the highest point in the hierarchy. Its place in the hierarchy is assigned based on the names passed to the getLogger function.

import logging
 
logger = logging.getLogger()
hello_logger = logging.getLogger('hello')
hello_world_logger = logging.getLogger('hello.world')
recommended_logger = logging.getLogger(__name__)

Logger names are similar to the names of the Python modules in which the dot separator is used. Their format is as follows:

hello – creates a logger which is a child of the root logger;

hello.world – creates a logger which is a child of the hello logger.

If you want to make another nesting, just use the dot separator.

The getLogger function returns a Logger object. Let's look at the example code in the editor. We'll find there the ways to get the Logger object, both with and without a name.

We recommend calling the getLogger function with the name argument, which is replaced by the current module name. This allows you to easily specify the source of the logged message.

NOTE: Several calls to the getLogger function with the same name will always return the same object.

  • info/cursos/pue/python-pcpp1/m5/4.1.1709550470.txt.gz
  • Darrera modificació: 06/07/2026 18:29
  • (edició externa)