Python Logging Module
In view of the complexity of recent projects, the simple print debugging method has been unable to meet the growing bug, so bloggers turned to logging.
First, basic usage
Can be used directly as print
# coding=utf-8import logginglogging.debug("debug message")logging.info("info message")logging.warning("warning message")logging.error("error message")logging.critical("critical message")‘‘‘WARNING:root:warning messageERROR:root:error messageCRITICAL:root:critical message默认只有级别高于warning的才会被打印,默认的Logger实例名为root‘‘‘
Output to File
# coding=utf-8import logging# 指定输出文件和输出级别logging.basicConfig(filename=‘root.log‘, level=logging.INFO)logging.debug("debug message")logging.info("info message")logging.warning("warn message")logging.error("error message")logging.critical("critical message")
Unlike the above results, the command line no longer has standard output (stdout), and the output is written to root.log
the log file
Second, custom log
The default configuration information is not rich enough, generally we add some information ourselves, logging can use Conf file, dictionary or directly configure three ways
First introduce the format, which provides additional information
format |
Description |
% (Levelno) s |
Print the value of the log level |
% (LevelName) s |
Print Log level name |
% (pathname) s |
To print the path of the current executing program |
% (filename) s |
Print the current name of the executing program |
% (FuncName) s |
Print the current function of the log |
% (Lineno) d |
Print the current line number of the log |
% (Asctime) s |
Time to print the log |
% (thread) d |
Print thread ID |
% (ThreadName) s |
Print Thread Name |
% (process) d |
Print Process ID |
% (message) s |
Print log information |
2.1 conf File
[loggers]keys = root[handlers]keys = stream_handler, file_handler[formatters]keys = formatter[logger_root]level = DEBUGhandlers = stream_handler, file_handler[handler_stream_handler]class = StreamHandlerlevel = DEBUGformatter = formatterargs = (sys.stderr,)[handler_file_handler]class = FileHandlerlevel = DEBUGformatter = formatterargs = (‘root.log‘, ‘a‘)[formatter_formatter]format = %(asctime)s - %(levelname)s - line %(lineno)d => %(message)s
# coding=utf-8import loggingfrom logging.config import fileConfig# 加载配置文件fileConfig(‘log.ini‘)logger = logging.getLogger()logger.debug(‘a new log‘)‘‘‘2018-08-18 23:51:15,277 - DEBUG - line 8 => a new log同时把结果写到root.log中‘‘‘
2.2 Dictionary Configuration
# coding=utf-8import loggingfrom logging.config Import dictconfiglogging_config = {' Version ': 1, ' formatters ' : {' F ': {' format ': '% (asctime) s-% (levelname) S-line% (lineno) d =% (message) s '}}, ' Handlers ': {' H1 ': {' class ': ' Logging. Streamhandler ', ' Formatter ': ' F ', # There is no level that defines the level to inherit root by default, ' H2 ': {' Class ': ' Logging. Filehandler ', ' Formatter ': ' F ', ' filename ': ' hello.log ', ' Level ': Logging. WARNING}}, ' root ': {' handlers ': [' H1 ', ' H2 '], # Level: Debug, Info, WARNING, error, critical ' Level ': Logging.info # Defines the minimum levels of processing}}dictconfig (logging_config) logger = Logging.getlogger () logger.debug (' Debug ') Logge R.info (' info ') logger.warning (' warning ') ' 2018-08-19 00:10:35,831-info-line/info2018-08-19 00:10:35,831-wa Rning-line warning the contents of warning are recorded in the Hello.log file '
'
2.3 Direct Configuration
This is relatively simple, direct code
# coding=utf-8import logginglogger = logging.getLogger()handler = logging.StreamHandler()formatter = logging.Formatter( ‘%(asctime)s %(name)s %(levelname)s %(message)s‘)handler.setFormatter(formatter)logger.addHandler(handler)logger.setLevel(logging.DEBUG)logger.debug(‘hi‘)‘‘‘2018-08-19 00:13:31,109 root DEBUG hi‘‘‘
Third, summary
Now we're out of the way. Based on print and single-step debugging method Good soil ... Log can greatly improve the efficiency of our debug, especially in tracking large projects can be used.
Python Logging Module