{"id":15849,"date":"2023-11-29T08:13:06","date_gmt":"2023-11-29T08:13:06","guid":{"rendered":"https:\/\/businessyield.com\/tech\/?p=15849"},"modified":"2023-11-29T08:58:30","modified_gmt":"2023-11-29T08:58:30","slug":"logging-in-python","status":"publish","type":"post","link":"https:\/\/businessyield.com\/tech\/technology\/logging-in-python\/","title":{"rendered":"LOGGING IN PYTHON: Everything You Need To Know","gt_translate_keys":[{"key":"rendered","format":"text"}]},"content":{"rendered":"

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!<\/p>

Overview<\/span><\/h2>

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.<\/p>

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

What Is Logging in Python?<\/span><\/h2>

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.<\/p>

How to Do Logging in Python<\/span><\/h2>

The various ways to log in python include the following:<\/p>

#1. Simple Logger<\/span><\/h3>

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.<\/p>

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.<\/p>

#2. Filtering Logs<\/span><\/h3>

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:<\/p>

#3. Logger<\/span><\/h3>

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.<\/p>

#4. Handlers<\/span><\/h3>

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.).<\/p>

#5. Formatters<\/span><\/h3>

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. <\/p>

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.<\/p>

#6. Filters<\/span><\/h3>

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

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.<\/p>

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.<\/p>

#7. Log levels<\/span><\/h3>

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. <\/p>

Python Logging Set Level <\/span><\/h2>

The six common Python logging set level includes the following:<\/p>