LOGGING IN PYTHON: Everything You Need To Know

LOGGING IN PYTHON
Image credit: Image by Freepik

The logging module in Python provides a flexible logging system that handles messages with varying levels of severity and allows for control over how to present them. This article provides an overview of how to do logging in Python, along with its set level. So, read on!

Overview

Logging is an important skill for programmers to have. It can help you understand how a program works better and find situations you might not have thought of while you were writing it. For developers, logs are like having an extra pair of eyes watching over the flow of an application all the time. They can keep track of things like which user or IP address visited the app. If there is an error, they can tell you more about what was going on with the program before it got to the line of code where the mistake happened than a stack trace. You can easily fix bugs if you log useful information in the right places. You can also use the information to look at how well the app works to plan for growth or at how people use it to plan for marketing.

Also, you can quickly add logging to your app with Python because it comes with a logging system with its standard tools. 

What Is Logging in Python?

Logging in Python permits the tracking of events during program execution. The addition of logs to an application’s code serves to record and report on various system occurrences. A message and some event-specific variable data define an event. You can use the native logging module in Python for this purpose. There are five different severity levels for log messages (DEBUG, INGO, WARNING, ERROR, and CRITICAL). They can also offer traceback data on exceptions. In the event of an issue, logs can be extremely helpful in pinpointing its origin.

How to Do Logging in Python

The various ways to log in python include the following:

#1. Simple Logger

The preceding code, when executed, would print “Hello world!” to the terminal just like a print command would. Despite the fact that this toy example doesn’t appear to provide any new features to printing, let’s take a look anyhow.

The initial step is spawning a new instance of Logger. After that, a StreamHandler is built, which writes all prompt logs by default. When the info method of the Logger instance is called, the word “Hello, world!” is sent to the console.

#2. Filtering Logs

A particularly handy component of logging statements is the numerous contextual levels they provide, allowing you to sort out log messages of different significance without reassigning the code. For instance, you might use an environment variable or setup file to configure the required log level. You can also use this to alter the logging module level during program execution and prevent the reporting of calls to lower-level loggers. It’s common practice to sprinkle.debug() calls around a particularly tough section of code when running in a test environment, but in a production setting, you might prefer to see only. error() and higher-level warnings. Without touching the code, you can set the logger levels to the appropriate state by using an environment variable. The name of this value could be LOG_LEVEL. Case in point:

#3. Logger

When logging, a new instance of Logger is generated. call to getLogger() is made. If called without parameters, this method will return a pointer to the logging module’s global root logger object. By giving a string indicating a name to getLogger() a child logger of the root logger is produced. In more advanced scenarios, it may be helpful to have logs propagate up a tree of connected parent and child loggers; however, that topic will not be addressed here. The Python Logging Cookbook and the Python Logging Documentation both have extra information on the topic of inherited log propagation.

#4. Handlers

A Logger instance’s handler is essential since it provides protocols for redirecting log messages to various destinations. Common handlers are StreamHandlers, which write to standard output and error streams like STDOUT and STDERR, and FileHandlers, which write data to files. When running code, it is natural to check the console for results. However, it is also advisable to log the output to a file in case the project is executed via a cron or by users in a distant location. I won’t go into detail about the many different kinds of handlers that exist (email, socket, rotating file, HTTP, etc.).

#5. Formatters

You can customize the format of every log message by including details like the line number, module name, function name, and time/date in formatter objects. Use these keywords in your Formatter string to include relevant background information in your message. 

If you work in a multithreaded environment, you can use the message’s formatting to indicate the thread or process it is sent from. As we demonstrated before, you can use the.setFormatter() method of the Handler class to attach a newly-created Formatter object to an existing Handler instance. Attach different Formatter objects to various handlers to customize the level of detail in your outputs. For instance, maybe you don’t want the module’s ID, function, and file name clogging up your console, therefore you could connect a formatter to it that doesn’t have those properties. However, I would like my file handler to have as much data as possible for better retrospective event reconstruction.

#6. Filters

Attached to Handlers, Filters allow for the suppression of messages coming from a lower Logger in the logging hierarchy than the Handler itself. 

Where base_logger.module_logger and base_logger.debug_logger defines the parent-child relationships of our loggers. Attaching a Filter object to a Logger prevents it from forwarding messages from that Logger’s parent logger. You can associate filter objects with individual handlers to have finer-grained control over which log messages are sent to which output destination.

For instance, you could link a Filter object to the base_logger and instruct it to disregard any messages recorded by the debug_logger. This will still allow messages from the module_logger to reach the base_logger and its handlers.

#7. Log levels

The severity of the Logger’s output can be adjusted via the Handler instance’s attribute. There are several ways to refer to the different log levels, but internally they are always represented by a decimal number. 

Python Logging Set Level 

The six common Python logging set level includes the following:

  • Error = 40: As the name suggests, a mistake has occurred. Some functions of the software were inoperable.
  • Notset = 0: When a log is created, this is the original default configuration. It is not really relevant, and most programmers will ignore it entirely. It has already become obsolete in many circles. Typically, the root log is created with the level WARNING.
  • Debug = 10: This level provides precise information that is only valuable for diagnosing a problem.
  • Info = 20: This is used to ensure that everything is functioning properly.
  • Critical = 50: A critical error has happened. The program itself may shut down or fail to function properly.
  • Warning = 30: This level suggests that something unusual has occurred or that a problem is due to occur in the near future.

In general, developers can set their own levels, but it’s not a good idea to do so. The levels in the lesson were made after many years of real-world experience, and they are meant to cover everything that needs to be covered. If a computer really wants to make its own levels, it should be very careful because the outcomes might not be great, especially if they are making a library. This is because when different library writers set their own custom levels, it will be very hard for the developer using the library to understand or control the logging data because the numbers can mean different things.

Why Do We Import Logging in Python?

Logging is a method used to store information about your script and keep track of events that take place. When writing complex scripts in Python, it is essential to incorporate logging for the purpose of debugging the software during the development process. Identifying the source of a problem in your code can be a time-consuming task if you don’t have proper logging in place.

Where Does Python Logging Output?

Python Logging Handler. A Python logging handler is a component used in the Python programming language to manage and control the logging process. It is responsible for capturing and processing log records, which are messages generated during the execution of The log handler is responsible for effectively writing and displaying a log. It can display the log in various ways, such as in the console using StreamHandler, in a file using FileHandler, or even by sending an email using SMTPHandler, among other options. Each log handler has two important fields: A formatter that enhances log entries by including relevant context information.

What Is the Fastest Logging Library for Python?

Picologging is a Python library that is designed to provide high-performance logging capabilities. The pico logging library is significantly faster than the logging module in the conventional library, with a speed improvement ranging from 4 to 17 times.

Does Logging Affect the Performance of Python?

If logging is consuming more than 1% of your processing time, it is likely that you are using it incorrectly, and this is not the fault of the logging system. Secondly, in relation to performance, it is advisable not to construct the message before sending it to the logging module. Instead, you should use the format command and pass the parameters directly.

What Is the Highest Level of Logging in Python?

The logging module in Python is a convenient tool that comes pre-installed. It offers a user-friendly interface and includes five levels of logging, each with increasing severity: debug (10) being the lowest level, and critical (50) being the highest.

In conclusion

Logging plays a crucial role in software development and programming languages. Logging is a valuable tool that can assist you in comprehending the actions performed by your program, identifying any errors that occurred, and determining the appropriate solutions to rectify them. As a Python developer, it is essential to have a good understanding of logging. Logging is a useful tool for evaluating and debugging your program. So, if you haven’t started logging in yet, now is the perfect time to begin your journey with Python.

References

We Also Recommend the Following

  1. How Do I Log Out of Facebook: Detailed Guide
  2. TOP BEST HDMI CABLE FOR PS5 IN 2023: Reviewed
  3. How To Remove Instagram Account From Phone: Simple Guide
  4. HOW TO CHANGE COLOR OF OBJECT IN PHOTOSHOP: 5 EASY Methods
  5. HOW TO CHANGE PASSWORD ON SPOTIFY: Detailed!
  6. RHINO3D: All To Know About Rhino 3D CAD Modeling Software
0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like