SoFunction
Updated on 2024-11-19

Process logging in Python using Log4j with the help of logging libraries

This article explains what log4j is, how it works and why we should use it. We will also learn how to use log4j in the Python programming language with the help of logging libraries.

An overview of Log4j and the importance of its use

log4j is a software used by programmers to help them when logging data in their applications. Moreover, logging data means recording the activities or operations performed in an application.

We can use log4j for security reasons, for example to look at various authentications. However, it can also be used to log what is happening in an application for debugging purposes.

Or a general idea of what the application has been doing. For example, log4j is a framework in the Java programming language that is a half-built application.

Similarly, in Python, we use the logging module instead of log4j. Logging is the process of recording application operations and state to a secondary interface. In other words, write your program operations to a file, but how do you start logging?

Then you need to familiarize yourself with logging levels. Each logging library allows you to target information at specific levels. There are five main logging levels that you must understand.

(military) rank clarification
debug The debug level is used for the development process or for bug fixing and troubleshooting. All developer-specific information is below this level.
info The information level is used to record any important default actions of the program, such as default user or system view actions.
warning The warning level is used to log events that may become errors in the long run. This logging level should help you track down errors.
error The error level is used to log errors, which are errors that would affect the execution of the program in some incorrect way.
critical The critical level is apocalyptic; the program is dead or severely corrupted.

Using Log4j with the help of the logging library in Python

Now we're just running a simple basic code with no such logic, but we want to show you some understanding of how to write all the logs to one file for example.

Let's get into the code and start by configuring the logging system by calling thebasicConfig() method, and pass in a filename with the filename argument. Python writes all log messages to this file; if it doesn't exist, Python creates it.

The next parameter is filemode, meaning file mode which means whether it is append mode to write mode or whatever you put, by default, the file will be created in append mode. The next parameter is the format of asctime, levelname, message and many other information.

asctime basically shows the type of time that it prints in this particular text file associated with the log. The second parameter value is something called levelname; this parameter tells us what kind of error occurred during execution.

This message is all the messages we are trying to print in this log message. We are using datefmt; this parameter will print the times in a specific order.

basicConfig() Functions have a different property, and we can read all about it here.

import logging
(filename='',
                    filemode='a',
                    format='%(asctime)s %(levelname)s-%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')
Now we have written a simple logic where we compare the percentile with some numbers and append some logs inside the text file.
for i in range(0,15):
    if i%2==0:
        ('Log error message')
    elif i%3==0:
        ('Log warning message')
    elif i%5==0:
        ('Log debug message') 
    elif i%7==0:
        ('Log critical message')
    else:
        ('Log info message')

Output:

2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 WARNING-Log warning message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 CRITICAL-Log critical message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 WARNING-Log warning message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 ERROR-Log error message
2022-09-01 23:21:28 ERROR-Log error message

After running the program, we can notice that no messages and debug logs are added to the text file because by default, levelname calls errors and the error level does not show messages and debugging.

However, we can use other levels by passing them with the level parameter.

level=

Now, if we run and open the file, we'll see all the log messages, but if we update the log level to , we'll see the error and critical messages.

2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 INFO-Log info message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 WARNING-Log warning message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 DEBUG-Log debug message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 CRITICAL-Log critical message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 WARNING-Log warning message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 INFO-Log info message
2022-09-01 23:23:57 ERROR-Log error message
2022-09-01 23:23:57 INFO-Log info message
2022-09-01 23:23:57 ERROR-Log error message

Let's look at a common problem where we want to divide any number by zero. To determine this operation, we will use a try block.

If the operation fails, we will go to the except block and display a log error.

try:
    1/0
except:
    ('Log zero division error occurs')

Output.

2022-09-02 00:29:48 ERROR-Log zero division error occurs

It is an important part of the project because you may have to write this logging mechanism whenever you deal with the project.

Complete Python code:

import logging
(filename='',
                    filemode='w',
                    format='%(asctime)s %(levelname)s-%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=)
# for i in range(0,15):
#     if i%2==0:
#         ('Log error message')
#     elif i%3==0:
#         ('Log warning message')
#     elif i%5==0:
#         ('Log debug message') 
#     elif i%7==0:
#         ('Log critical message')
#     else:
#         ('Log info message')
try:
    1/0
except:
    ('Log zero division error occurs')

This article on the use of Log4j in Python with the help of logging libraries to this article, more related to the use of Python Log4j logging library Log4j content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!