Good article on python logging

Basic usage:
 
import sys
 
# Get the logger instance, if the parameter is empty, return the root logger
logger = logging.getLogger("AppName")
 
# Specify the logger output format
formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
 
# file log
file_handler = logging.FileHandler("test.log")
file_handler.setFormatter(formatter) # You can specify the output format through setFormatter
 
# console log
console_handler = logging.StreamHandler(sys.stdout)
console_handler.formatter = formatter # You can also assign values ​​to formatter directly
 
# Log handler added for logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)
 
# Specify the minimum output level of the log, the default is WARN level
logger.setLevel(logging.INFO)
 
# output log of different levels
logger.debug('this is debug info')
logger.info('this is information')
logger.warn('this is warning message')
logger.error('this is error message')
logger.fatal('this is fatal message, it is same as logger.critical')
logger.critical('this is critical message')
 
# 2018-04-08 21:59:19,493 INFO    : this is information
# 2018-04-08 21:59:19,493 WARNING : this is warning message
# 2018-04-08 21:59:19,493 ERROR   : this is error message
# 2018-04-08 21:59:19,493 CRITICAL: this is fatal message, it is same as logger.critical
# 2018-04-08 21:59:19,493 CRITICAL: this is critical message
 
# remove some log handlers
logger.removeHandler(file_handler)
 
 
 
Formatting output tips
# formatted output
 
service_name = "Booking"
logger.error('%s service is down!' % service_name) # Use python's own string formatting, not recommended
logger.error('%s service is down!', service_name) # Use logger format, recommended
logger.error('%s service is %s!', service_name, 'down') # Multiple parameter formatting
logger.error('{} service is {}'.format(service_name, 'down')) # Use the format function, recommended
 
# 2018-04-08 21:59:19,493 ERROR   : Booking service is down!
 
 
 
logging.basicConfig
  basicConfig() Provides a very convenient way for you to configure the logging module and start using it right away
 
 
import logging
 
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
 
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
 
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
 
 Note: In fact, you can even use the default value to log in the console without configuring anything. Replacing the print statement in this way will be very helpful for future project maintenance.
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939175&siteId=291194637