Using Log4j in Python with a logging library


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


An overview of Log4j and the importance of its use

log4j is a piece of software used by programmers to help them when logging data in their applications. Also, logging data means logging the activities or actions performed in the application.

We can use log4j for security reasons, for example to see various authentications. However, it can also be used to log what's happening in the application for debugging purposes.

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

Also, in Python, we used the logging module instead of log4j. Logging is the process of recording application actions and state to a secondary interface. In other words, your program's operations are written to a file, but how do you start logging?

Well, you need to be familiar with logging levels. Each logging library allows you to lock down information at a specific level. There are five main logging levels that you must understand.

level illustrate
debug Debug level is used during development or for bug fixing and troubleshooting. All developer-specific information is below this layer.
info The info level is used to log any significant 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 Error levels are used to log errors, which are errors that affect program execution in some wrong way.
critical Critical level is the end of the world; the program is dead or badly broken.

Using Log4j with the help of a logging library in Python

Right now we're just running a simple basic code, and there's no such logic, but we want to show you some understanding, like how to write all logs to a file.

Let's get into the code, first configure the logging system, call basicConfig()the method, and pass in the filename using the filename parameter. Python will write all log messages to this file; if it does not exist, Python will create it.

The latter parameter is filemode, which means file mode means append mode to write mode or whatever you put in. By default, the file will be created in append mode. Next is the format representing asctime, levelname, message and many other information.

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

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

basicConfig()Functions have a different property from which we can read all properties.

import logging

logging.basicConfig(filename='demo.txt',
                    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:
        logging.error('Log error message')
    elif i%3==0:
        logging.warning('Log warning message')
    elif i%5==0:
        logging.debug('Log debug message') 
    elif i%7==0:
        logging.critical('Log critical message')
    else:
        logging.info('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 info and debug logs are not added in the text file, because by default, levelname calls error and errorlevel does not show info and debug.

However, we can use other levels by using the level parameter when passing logging.DEBUG.

level=logging.DEBUG

Now, if we run and open the demo.txt file, we will see all the log messages, but if we update the log level to logging.ERROR, we will see 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 action, we'll use a try block.

If the operation fails, we enter the except block and log the error.

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

output:

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

It's an important part of your project because you'll probably have to write this logging mechanism whenever you work on a project.

Complete Python code:

import logging

logging.basicConfig(filename='demo.txt',
                    filemode='w',
                    format='%(asctime)s %(levelname)s-%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.DEBUG)

# for i in range(0,15):
#     if i%2==0:
#         logging.error('Log error message')
#     elif i%3==0:
#         logging.warning('Log warning message')
#     elif i%5==0:
#         logging.debug('Log debug message') 
#     elif i%7==0:
#         logging.critical('Log critical message')
#     else:
#         logging.info('Log info message')

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

Guess you like

Origin blog.csdn.net/fengqianlang/article/details/131584939
Recommended