Introduction to logging module
The logging module is a standard library module of Python. During the development process, this module can be used to flexibly complete log recording.
The logging module provides two logging methods:
1) Use the module-level functions provided by logging (logging.basicConfig, logging.debug, logging.info...)
2) Use the components of the logging module (loggers, handlers, filters, formatters)
Python logging log level
level | Corresponding function | description |
---|---|---|
DEBUG | logging.debug() | The lowest level, used for small details, usually only when diagnosing problems, you will only care about these messages. |
INFO | logging.info() | Used to record information about general events in the program, or to confirm that everything is working properly. |
WARNING | logging.warning() | Used to indicate possible problems. It will not prevent the program from working, but it may in the future. |
ERROR | logging.error() | Used to log errors, it causes the program to fail to do something. |
CRITICAL | logging.critical() | The highest level, used to indicate a fatal error, which caused or will cause the program to stop working completely. |
Instance
import logging
from logging.handlers import TimedRotatingFileHandler
class RecordLogs:
def __init__(self, log_name, level=20, log_format="%(asctime)s,%(msecs)d %(name)s:%(levelname)s: [%(module)s(%(lineno)d)] %(message)s",
date_format="%Y-%m-%d %H:%M:%S", console_print=True, log_file=None, when=None):
self.log_name = log_name
self.level = level
self.log_format = log_format
self.date_format = date_format
self.console_print = console_print
self.log_file = log_file
self.when = when
def print(self):
# avoid duplicate printing
if not self.console_print and not self.log_file:
print("Error: Save log in file, but input not log file!")
return
log_dict = logging.Logger.manager.loggerDict
print_flag = True if self.log_name not in log_dict else False
when = None if self.when not in ["S", "M", "H", "D", "midnight"] else self.when
if not print_flag:
return
# create logger
logger = logging.getLogger(self.log_name)
logger.setLevel(self.level)
formatter = logging.Formatter(self.log_format, self.date_format)
if self.console_print:
# create handler,output log to console
log_sh = logging.StreamHandler()
log_sh.setFormatter(formatter)
# logger add handler
logger.addHandler(log_sh)
if self.log_file:
if when:
logHandler = TimedRotatingFileHandler(self.log_file, when=when)
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)
else:
fh = logging.FileHandler(self.log_file)
fh.setFormatter(formatter)
# logger add handler
logger.addHandler(fh)
return logger
if __name__ == "__main__":
import time
test_log = RecordLogs("log_test", console_print=True, log_file="C:/Users/user/Desktop/test.log", when=None, level=10).print()
while True:
test_log.info("info logger")
test_log.error("error logger")
test_log.warning("warning logger")
test_log.debug("debug logger")
time.sleep(10)
result:
to sum up:
The log printed during the running of the program through this module, especially the error information, is very important for troubleshooting, otherwise you have to manually execute the program every time to reproduce it again, which is very troublesome!