Linux

Python loggers

Logging is a means of tracking events that happen when some software runs. Logging provides a set of convenience functions for simple logging usage. These are debug(), info(), warning(), error() and critical(). To determine when to use logging,

You can use print statement to debug if it comes to get output on screen, but if you want output on a log file. OK you can write output on a file. But again and again open a file is time consuming or in case of multithreading it is very tedious task to take output on file. Here we are going to discuss how you can make your own logger.

Creating a Simple Logger

In this section you will learn how to create a Python simple logger. Let us start from very basic with basicConfig.

Empty Python Tuple

Example 1 :

import logging
logging.basicConfig(filename="live.log",filemode="w", level=logging.DEBUG)
logging.debug("This is a debug message")
logging.info("Informational message")
logging.warning("A warning!")
logging.error("An error has happened!")
logging.critical("Critical !!!!")
Out-put
Basic Python logger
Basic Python logger

The easiest way to create a log is to use the logging module's basicConfig function. filename, filemode, format, datefmt, level and stream. In our example, we pass it a file name and the logging level, which we set to DEBUG. There are five levels of logging (in ascending order): DEBUG, INFO, WARNING, ERROR and CRITICAL.

Let us run the program with level warning.

Example 2 :

import logging
logging.basicConfig(filename="live.log",filemode="w", level=logging.WARNING)
logging.debug("This is a debug message")
logging.info("Informational message")
logging.warning("A warning!")
logging.error("An error has happened!")
logging.critical("Critical !!!!")
Out-put
Basic Python logger
Basic Python logger level warning

You can see only error, warning and critical are printed, its due to ascending order. The root part signifies that this logging message is coming from the root logger or the main logger.


In order to make more descriptive don't use basicConfig. See the following example.

Example 3:

import logging
import time
logger = logging.getLogger("L4wisdom")
logger.setLevel(logging.INFO)
fh = logging.FileHandler("live1.log")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
Here we create a logger instance named "L4wisdom". set a level, create a logging file handlers, add handler to logger object
Logger is created, Now save program as logger1.py.
Let us make another program log1.py.

Example 4:

import logging
import logger1
import time
i=0
while True:
i = i+1
logger1.logger.info(i)
logger1.logger.error(i)
logger1.logger.warning(i)
logger1.logger.debug(i)
time.sleep(2)
Out-put
formate Python logger
Python logger

Just make one logger module and import in all programs, no need to write logger again and again.






admin