logging module print log

Keywords: encoding

https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00138683229901532c40b749184441dbd428d2e0f8aa50e000

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
  1. #https://www.cnblogs.com/nancyzhu/p/8551506.html
  2. #https://blog.csdn.net/sollor525/article/details/79152526
  3. #--coding:UTF-8--
  4. import logging
  5. log_format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
  6. date_format = "%m/%d/%Y %H:%M:%S %p"
  7. filemode='a' ##a is the append mode, which defaults to the append mode; w is the write mode, which overwrites previous logs
  8. 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
  9. logging.debug('debug')
  10. logging.info('info')
  11. logging.warning('warning')
  12. logging.error('error')
  13. logging.critical('critial')
Write to Log all.log, And can print out
  1. #https://www.cnblogs.com/nancyzhu/p/8551506.html
  2. import logging
  3. from logging import handlers
  4. class Logger(object):
  5. level_relations = {
  6. 'debug':logging.DEBUG,
  7. 'info':logging.INFO,
  8. 'warning':logging.WARNING,
  9. 'error':logging.ERROR,
  10. 'crit':logging.CRITICAL
  11. }#Log Level Relationship Mapping
  12. def __init__(self,filename,level='info',when='D',backCount=3,
  13. fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
  14. self.logger = logging.getLogger(filename)
  15. format_str = logging.Formatter(fmt)#Format Log
  16. self.logger.setLevel(self.level_relations.get(level))#Set Log Level
  17. sh = logging.StreamHandler()#Output to screen
  18. sh.setFormatter(format_str) #Format screen display
  19. th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#Write to File#Processor that automatically generates files at specified intervals
  20. #Instantiate TimedRotatingFileHandler
  21. #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:
  22. # W Every week ( interval==0 Time Representation Monday) # midnight every morning
  23. th.setFormatter(format_str) #Format Writes in Files
  24. self.logger.addHandler(sh) #Add objects to logger
  25. self.logger.addHandler(th)
  26. if __name__ == '__main__':
  27. log = Logger(filename='all.log',level='debug') #filename='all.log' level='debug'
  28. log.logger.debug('debug')
  29. log.logger.info('info')
  30. log.logger.warning('warning')
  31. log.logger.error('Report errors')
  32. log.logger.critical('serious')
  33. #Logger('error.log', level='error').logger.error('error')
Write to Log log1.log, And can print out
  1. #https://www.cnblogs.com/deeper/p/7404190.html
  2. import logging
  3. logger = logging.getLogger(__name__)
  4. logger.setLevel(level = logging.INFO)
  5. handler = logging.FileHandler("log1.txt")
  6. handler.setLevel(logging.INFO)
  7. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  8. handler.setFormatter(formatter)
  9. console = logging.StreamHandler()
  10. console.setLevel(logging.INFO)
  11. logger.addHandler(handler)
  12. logger.addHandler(console)
  13. logger.info("Start")
  14. logger.debug("debug")
  15. logger.warning("fail")
  16. logger.info("Finish")



Posted by cyball on Sun, 05 May 2019 23:40:38 -0700