Python

Python Logging SetLevel

The common library’s Logging Python package offers the ability to deal with the framework for issuing the log information from Python programs. Logging is mostly important to keep track of data, errors, and exceptions. It aids in debugging as well. Logging is the simple term for anything we track and collect. Therefore, gathering information, both that which we already have and that which we will get throughout processing, will help us in debugging. In logging, there are five predetermined levels which will be discussed in this article.

Working on Logging In to Python

As with an application admin login, the time and name are entered into a file which is then logged by saving the file. This implies that as long as our data is being collected, we will know who the admin is logged in at that time, and we will be able to save his logout information as well. Therefore, this is an essential information that we may record and save in a log file for any admin login or logout moments. Similar to this, we occasionally encounter a specific error in the code. To address this, we create a log, enter the relevant data and information, and set up the scenario such that if the error occurs, an error message is displayed. Once this happens, the message is saved on the log file which we can access to see the log file and quickly identify and correct the error. Logging is typically defined the same way in all computer languages. We must use the Python’s logging module if we wish to keep track of errors. The logging library for Python needs to be imported as shown in the following picture:

We can also import the logging by writing “from logging import *”. Moving on, let’s talk about the Python logging setLevel method.

BasicConfig (**kwargs) Method

The logging system is configured using this technique.

Syntax for the BasicConfig:

We can utilize the “basicConfig( )’s” numerous parameters in the parentheses. Consequently, let’s talk about its parameters and define each one’s purpose.

filename: Instead of constructing a stream handler, it directs that a FileHandler be constructed with the supplied filename. This argument is used to specify the name of the newly generated log file, and its value is the name of the file which is put within the parentheses. We can also utilize the path, which indicates the location in which we want to create a file, using the “filename” parameter. The order in which this argument is written is “filename” first, then the equals sign (“=”), then the inverted commas. We give our with file any name that we choose by placing it between the inverted commas.

filemode: Open the file in this mode if the filename is provided – “a” is by default but “w” can be written as well. This indicates the default mode in which the file is created, which is the appended mode. However, we can alternatively open the file in write mode by writing “w”.  A file can be opened in write mode by first writing the “filemode”, then using the equals sign (“=”), and then writing the “w” in between the inverted commas. The prior data is likewise visible in the file when we open it in the appended mode, but it will be removed when we open it in the write mode.

Level: Set the level of the root logger as desired. There are different levels produced in it such as an “info” level, “debug” level, “warning” level, “error” level, and “critical” level.

format: Use the selected handler’s format string. The data that is kept in the log file has a specific format because we set it accordingly.

datefmt: Use the date and time format that has been defined over “time.strftime()”. We described the date and time format in simple words.

Style: Use this style for the format string if the format is provided with a “%”, “{“, or “$” for print-style, str.format(), or string, respectively. The appropriate template is usually set to “%”.

There are many more parameters apart from these such as “stream”, “handlers”, and “force” but we won’t utilize them in this context.

Levels of Logging

The Python standard library also includes the logging module. We only need to import logging to get started. There are five common logging levels that, by default, represent the importance of occurrences. These levels are:

  1. NOTESET – Its level in numeric is 0
  2. DEBUG – Its level in numeric is 10
  3. INFO – Its level in numeric is 20
  4. WARNING – Its level in numeric is 30
  5. ERROR – Its level in numeric 40
  6. CRITICAL – Its level in numeric 50

Our level is by default set to “30” which is in the “Warning” category. We can display “Warning”, “Error”, and “Critical” in our log file because our default level set is “30” which is “warning”. But we cannot display “Debug” and “Info”.  To display “Info” and “Debug,” we must first alter the level to “Debug” where all data above that level are entered. At the moment, the level is a warning, so all data above that level are entered.

Let’s now begin to put the script into action. First, we import logging which implies that everything from the logging module is imported. Then, in the following line, we use the “logging.debug” and pass the message “This is a debug message” in its parenthesis. Then, in the following line, we use the “logging.info” and pass the message “This is an informational message”. Both of these are the setLevels, but they won’t show up in the console because the default level is “30” which is a “warning”. As a result, the console shows the data above from the warning whose numeric levels are “40” and “50”.

You can see that it won’t display anything in the output because we use the “debug” and “info” level. The level was set to “warning” by default “level 30”.

The message “This is a warning message” was provided to the “logging.warning” in the second section of the code where we now use the remaining levels of logging. Then, in the following line, we use the “logging.error” and pass the phrase “This is an error message” within its parentheses. Next, we use the “logging.critical” and pass the phrase “users are in difficulties” within its parentheses. Now, when we execute this script, it displays the warning, error, and critical messages since the default setLevel is “30” which is a warning. It does not display the debug or info messages because they are below the warning level.

Now that the default text is displayed, as you can see in the following image, it is displayed in a log file. Therefore, the “warning”, “error”, and “critical” levels are shown here. “Root” is the logger name. After that, the message is shown. We explained why the “debug” and “info” levels are not displayed in the previous explanation.

To store or display all of the data above from the debug including “debug”, “info”, “warning”, “error”, and “critical”, we now set the “debug” level to display the data above from the debug. Since we used the “logging.basicConfig” for this purpose and gave the “level=”DEBUG” as its value, the output now displays all levels and messages:

The output successfully shows all the levels. The data above the debug is shown, the levels’ names are shown, first the logger is the root, and then the messages are shown.

Now, we demonstrate how the messages are formatted. Format accepts a string with any combination of LogRecord properties. We gave the format to the same script in the next step. For this, after importing logging, we use the “log format” in the following line. Then, we use a string with “LogRecord” attributes in the order that we like. First, we use “asctime”. Because it is in a string, we use “s”. And we use the percentage symbol because we use the percentage style. Then, we use the “levelname” which displays the name of the level. Then, we use “name” which displays the logger name. Then, we use “lineno” which displays the number of the line.  Let’s execute the script now.

It shows the formatting that was specified in the script. The date and time were displayed first, then the level names, the first level being “Debug” and the logger name, “root”. After then, it displays “7” as its line number before showing the message because, as you can see in the previous script, the word “debug” is used in line seven. Similar message formatting is shown for the remaining levels.

Conclusion

In this article, we covered the Python logging setLevels. We have a total of six set levels, and we talked about five of them: “debug”, “info”, “warning”, “error”, and “critical”. Our level is by default set to “30” which is the level warning, so it displays the data above the warning.   We discussed in this article that we can also display the data of “debug” and above from the debug by setting the basicConfig level to debug. We additionally discussed how to format the messages at different levels using the “LogRecords” attributes.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.