One 、 Necessary skills
1、logging Use of modules
Two 、logging
1、logging Basic use of
1.1、 The five levels of logs (DEBUG/INFO/WARNING/ERROR/CRITICAL)
1.2、 How to print different log levels :
2、 Custom log collector
2.1、 Create a log collector
summary
One 、 Necessary skills 1、logging Use of modules(1)5 Log levels / as well as 5 Built in functions for outputting logs
(2) Log collector 、 The concept of log output channel
(3) How to customize the log collector
(4) How to encapsulate a custom log collector
Two 、loggingpython The official library of , For printing logs , No installation required , Call directly when using
1、logging Basic use of 1.1、 The five levels of logs (DEBUG/INFO/WARNING/ERROR/CRITICAL)(1)DEBUG: Logs in debug mode , Logs for programmers only
(2)INFO: The log output when the program is running normally
(3)WARN/WARNING: Warning message , The current program can also run , There may be problems later
(4)ERROR: The total error message during program execution
(5)CRITICAL: A serious error has occurred , Blocking the flow , The program may not continue
1.2、 How to print different log levels :(1)logging.debug(" Debug log information ")
(2)logging.info(" Important log information ")
(3)logging.warning(" Warning log information ")
(4)logging.error(" Error log information ")
(5)logging.critical(" Fatal log information ")
1.3、 Log collector and log output channel :
Log collector :
The default collector name is root, The default collection level is WARNING, Set the level of the collector by following the steps below
log = logging.getLogger() # Get log collector , The default is root
log.setLevel(" Grade ") # The grade must be capitalized
logging.basicConfig(level=logging.DEBUG) # Set the level of the collector
Log output channel :
The default output level is WARNING
Output channel support : Output to folder and output to console
Demo example 1—— Default WARNING Grade
import logging# Print different levels of logs (debug、info、warning、error、critical)# as follows 5 Logs , Only print WARNING Log after level logging.debug(" This is a piece. debug Level of logging ")logging.info(" This is a piece. info Level of logging ")logging.warning(" This is a piece. warning Level of logging ")logging.error(" This is a piece. error Level of logging ")logging.critical(" This is a piece. critical Level of logging ")
Running results :( Only print WARNING Log above level )
WARNING:root: This is a piece. warning Level of logging
ERROR:root: This is a piece. error Level of logging
CRITICAL:root: This is a piece. critical Level of logging
Demo example 2—— Default collector log
import logging# # logging.basicConfig(level=logging.DEBUG) Set the log level # Not specified name, By default, the default is returned root The collector # Default output WARN Level logs above level # If set WARNING The following levels , The output WARNING Log above level # If set WARNING Above grade , Let's say I set ERROR, The output ERROR Log above level log = logging.getLogger()# log.setLevel("DEBUG")# log.setLevel("INFO")# log.setLevel("WARNING")log.setLevel("ERROR")# log.setLevel("CRITICAL")logging.debug(" This is a piece. debug Level of logging ")logging.info(" This is a piece. info Level of logging ")logging.warning(" This is a piece. warning Level of logging ")logging.error(" This is a piece. error Level of logging ")logging.critical(" This is a piece. critical Level of logging ")
Running results :
2、 Custom log collector 2.1、 Create a log collectorERROR:root: This is a piece. error Level of logging
CRITICAL:root: This is a piece. critical Level of logging
log = logging.getLogger(name="rose_logger")
Don't pass on name When parameters are , The default returned collector name is “root”
Yes name When parameters are , A new log collector will be created
2.2、 Create a log collection channel
(1) Output to console :
pycharm = logging.StreamHandler()
(2) output to a file :
file = logging.FileHandler(os.getcwd()+r"\rose.log",encoding="utf-8")
file=handlers.TimedRotatingFileHandler(filename="test.log",when="D",interval=1,backupCount=10,encoding="utf-8")
Be careful ( Parameters ):
filename, The file name of the log ( Inclusion path )
when= 'h', The cutting unit of the log
# S - Seconds second
# M - Minutes minute
# H - Hours Hours
# D - Days God (24 Hours )
# midnight - roll over at midnight Sun cut
# W{0-6} - roll over on a certain day; 0 - Monday Zhou
interval=1, Rolling cycle , And when='h' verb-sequence ,1- It means taking time as a period
backupCount=0 Number of reserved log files , Set to 10, Always save only the latest 10 File
2.3、 Create the output format of the log (1) Create a log format object
pycharm_fmt = logging.Formatter(fmt=fmt1)
(2) Bind the log output format to the log output channel
pycharm.setFormatter(fmt=pycharm_fmt) —— Set the log channel to the console
file.setFormatter(fmt=pycharm_fmt1)—— Set to file log channel
(3) Common format templates ( You can also define )
fmt1 = "%(asctime)s - [%(funcName)s-->line:%(lineno)d] - %(levelname)s:%(message)s"
fmt2 = '[%(asctime)s-%(name)s-%(levelname)s-%(filename)s-%(lineno)d]:%(message)s'
(4) The format must be in the specified format . Common ones are as follows :
%(asctime)s—— current time
%(funcName)s—— Module name
%(lineno)d—— Line number
%(levelname)s—— Log level name
%(message)s—— Specific log content
Demo example 3—— Customize the log collector and log format
import logging,osfrom logging import handlers# 1、 Create a log collector log = logging.getLogger(name="rose_logger")# 2、 Create a log collection channel # Output console pycharm = logging.StreamHandler()# Output folder file = logging.FileHandler(os.getcwd()+r"\rose.log",encoding="utf-8")# file = handlers.TimedRotatingFileHandler(filename="test.log",when="D",interval=1,backupCount=10,encoding="utf-8")# 3、 Create the output format of the log fmt1 = "%(asctime)s - [%(funcName)s-->line:%(lineno)d] - %(levelname)s:%(message)s"# Create a log output object pycharm_fmt = logging.Formatter(fmt=fmt1)fmt2 = '[%(asctime)s-%(name)s-%(levelname)s-%(filename)s-%(lineno)d]:%(message)s'pycharm_fmt1 = logging.Formatter(fmt=fmt2)# 4、 The log output format is bound to the log output channel pycharm.setFormatter(fmt=pycharm_fmt)file.setFormatter(fmt=pycharm_fmt1)# 5、 Just set the logging level for the collector , The channel will inherit the log level of the collector log.setLevel(level=logging.DEBUG)# 5、 Set the log level for the collection channel , Document channel , The level of console output will not be the same # pycharm.setLevel(logging.DEBUG)# 6、 Bind the log collection channel to the log collector log.addHandler(pycharm)log.addHandler(file)log.info(msg=" test ")
Output results :
Demo example 4—— Encapsulate custom log collectors
import loggingfrom logging import handlersdef create_log(name,level,filename,sh_level,fh_level): """ :param name: Log collector name :param level: The level of the log collector :param filename: The name of the log file :param sh_level: Level of console output log :param fh_level: File output log level :return: Return to the created log collector """ # 1、 Create a log collector log = logging.getLogger(name) # 2、 Create the level of the log collector log.setLevel(level=level) # 3、 Create log collection channels and levels sh = logging.StreamHandler() sh.setLevel(level=sh_level) log.addHandler(sh) fh = logging.FileHandler(filename=filename,encoding="utf-8") # fh1 = handlers.TimedRotatingFileHandler(filename=filename,when="D",interval=1,backupCount=10,encoding="utf-8") fh.setLevel(level=fh_level) log.addHandler(fh) # 4、 Format log output formats = "%(asctime)s - [%(funcName)s-->line:%(lineno)d] - %(levelname)s:%(message)s" log_format = logging.Formatter(fmt=formats) sh.setFormatter(log_format) fh.setFormatter(log_format) return logif __name__ == '__main__': log = create_log(name="rose_log",level=logging.DEBUG,filename="test_log.log",sh_level=logging.DEBUG,fh_level=logging.DEBUG) log.info(msg="--------debug--------") log.info(msg="--------info--------") log.info(msg="--------warning--------") log.info(msg="--------error--------") log.info(msg="--------critical--------")
Output results :
summaryThis is about python This is the end of the article on the use of the log printing method , More about python Please search the previous articles of the software development network or continue to browse the following related articles. I hope you can support the software development network in the future !