https://www.cnblogs.com/nancyzhu/p/8551506.html
https://www.cnblogs.com/deeper/p/7404190.html
https://blog.csdn.net/sollor525/article/details/79152526
1. Print to console
import logging logging.debug('debug information') logging.warning('Only this will output.)') logging.info('info information')
Since the default level is warning, all warning-only information is output to the console.
WARNING:root: Only this will output.
Use logging.basicConfig() to print information to the console
import logging logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s', level=logging.DEBUG) logging.debug('debug information') logging.info('info information') logging.warning('warning information') logging.error('error information') logging.critical('critial information')
Since the value of level in logging.basicConfig() is set to logging.DEBUG, all debug, info, warning, error, critical logs are printed to the console.
So if level = logging.info() is set, the debug information is not output to the console.
2. Save log to file using logging.basicConfig()
logging.basicConfig(level=logging.DEBUG, #log level for console printing) filename='new.log', filemode='a', ##mode, w and a are write modes, each time the log is rewritten, overwriting the previous log #a is the append mode, which is the default if not written format= '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' #Log format )
If you set filename and filemode in logging.basicConfig(), only the log is saved to a file and not to the console.
Four components of logging log module
Before introducing the log stream processing flow of the logging module, let's first introduce the four components of the logging module:
Component Name | Corresponding Class Name | Functional Description |
---|---|---|
Logger | Logger | Provides an interface that applications can always use |
processor | Handler | Send log records created by logger to appropriate destination output |
Filter | Filter | A finer-grained control tool is provided to determine which log records are output and which are discarded |
Formatter | Formatter | Determining the final output format for logging |
If logging.basicConfig()Set up filename and filemodeļ¼Then only save log To a file, not to the console.
Write to Log my.log, Unable to print out
#https://www.cnblogs.com/nancyzhu/p/8551506.html #https://blog.csdn.net/sollor525/article/details/79152526 #--coding:UTF-8-- import logging log_format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' date_format = "%m/%d/%Y %H:%M:%S %p" filemode='a' ##a is the append mode, which defaults to the append mode; w is the write mode, which overwrites previous logs logging.basicConfig(filename='my.log', filemode='a', level=logging.INFO, format=log_format) #Format-Sets the print output format, a is the append mode, default if not written, is the append mode logging.debug('debug') logging.info('info') logging.warning('warning') logging.error('error') logging.critical('critial')
Write to Log all.log, And can print out
#https://www.cnblogs.com/nancyzhu/p/8551506.html import logging from logging import handlers class Logger(object): level_relations = { 'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'crit':logging.CRITICAL }#Log Level Relationship Mapping def __init__(self,filename,level='info',when='D',backCount=3, fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'): self.logger = logging.getLogger(filename) format_str = logging.Formatter(fmt)#Format Log self.logger.setLevel(self.level_relations.get(level))#Set Log Level sh = logging.StreamHandler()#Output to screen sh.setFormatter(format_str) #Format screen display th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#Write to File#Processor that automatically generates files at specified intervals #Instantiate TimedRotatingFileHandler #Interval is the time interval, backupCount is the number of backup files, if more than this number, will be automatically deleted, when is the unit of time interval, there are several units: # W Every week ( interval==0 Time Representation Monday) # midnight every morning th.setFormatter(format_str) #Format Writes in Files self.logger.addHandler(sh) #Add objects to logger self.logger.addHandler(th) if __name__ == '__main__': log = Logger(filename='all.log',level='debug') #filename='all.log' level='debug' log.logger.debug('debug') log.logger.info('info') log.logger.warning('warning') log.logger.error('Report errors') log.logger.critical('serious') #Logger('error.log', level='error').logger.error('error')
Write to Log log1.log, And can print out
#https://www.cnblogs.com/deeper/p/7404190.html import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log1.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(handler) logger.addHandler(console) logger.info("Start") logger.debug("debug") logger.warning("fail") logger.info("Finish")