Using Logging in Python

Logging is a useful tool in the development process because it allows your code to capture events as they occur during program execution for subsequent study. It constantly collects data on how things are working. Furthermore, if anything unexpected occurs, you may use the log to assist in pinpointing the problem in your software. It's also not always viable or feasible to use a standard debugger to walk through the code of your application to assist in examining and fixing problems in real time. For example, the code may be executed on a distant server, making local debugging impossible. Furthermore, certain types of mistakes and difficulties only occur on rare occasions during the program's lifespan. Logging allows you to easily categorize numerous events that occur while your software is running, which might help you track down the source of a problem. Even if logging isn't used for debugging, it can offer a helpful audit record of the program's execution for business analysis. It's also quite simple to change the output format of logged data. As a result, you may enter information in as extensive or as basic a manner as you choose.

Logging Levels

data set me.png

Custom Logging

The basic config function takes two additional arguments, format and datefmt.

basicConfig(
    format = formatstr,
    datefmt = date_format_str
)

The format argument specifies a string that controls the precise formatting of the output message that is sent to the log. The date format argument is used in conjunction with the format argument.

Some of the formatting tokens you can use in the format argument:

generating random values.png

import logging

def main():
    logging.basicConfig(filename="output.log",
                        level=logging.DEBUG)

    logging.info("This is a info-level log massage")
    logging.warning("This is a warning-level massage")

if __name__ == "__main__":
    main()

Output in the "output.log" file:

INFO:root:This is a info-level log massage
WARNING:root:This is a warning-level massage