logging The module is used to output the running log , Different log levels can be set , Save information to a log file . comparison print,logging You can set the level of the log , Control the output in the release , And you can specify the output format of the log .
1. Use logging Output log at terminal
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # introduce logging modular
# Set print log level CRITICAL > ERROR > WARNING > INFO > DEBUG
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s
-%(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
# Print the information to the console
logging.debug(u" debugging ")
logging.info(u" Perform the printing function ")
logging.warning(u" Warning ")
logging.error(u" error ")
logging.critical(u" Fatal error ")
Output
2. Use logging Output log at the terminal , And save the log locally log file
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging # introduce logging modular
import os.path
# First step , Create a logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Log Grade switch
# The second step , Create a handler, For writing log files
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
log_name = log_path + 'log.log'
logfile = log_name
file_handler = logging.FileHandler(logfile, mode='a+')
file_handler.setLevel(logging.ERROR) # Output to file Of log Level switch
# The third step , Definition handler The output format of
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_handler.setFormatter(formatter)
# Step four , take handler Add to logger Inside
logger.addHandler(file_handler)
# If you need to output it on the terminal at the same time , Define a streamHandler
print_handler = logging.StreamHandler() # Output... To the screen
print_handler.setFormatter(formatter) # Format the display on the screen
logger.addHandler(print_handler)
# Log information
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
# Or use logging
logging.debug('this is a logger debug message')
logging.info('this is a logger info message')
logging.warning('this is a logger warning message')
logging.error('this is a logger error message')
logging.critical('this is a logger critical message')
Log hierarchy
traceback yes python The module used to track exception information in , It is convenient to print the exception in the program .
Common use
try:
doSomething()
except:
traceback.print_exc()
# logging.error(str(traceback.format_exc()))
traceback.format_exc() And traceback.print_exc() difference :
traceback.print_exc() You can also write exception information to a file , Usage method :
traceback.print_exc(file=open('traceback_INFO.txt','w+'))