Configuration file:
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 """4 Logging Configuration5 """6 7 ImportOS8 ImportLogging.config9 Ten #define three types of log output formats to start with One AStandard_format ='[% (asctime)-S] [% (ThreadName) s:% (thread) d][task_id:% (name) s][% (filename) s:% (Lineno) d]' - '[% (LevelName) s] [% (message) s]' - theSimple_format ='[% (LevelName) s] [% (asctime) s][% (filename) s:% (Lineno) d]% (message) s' - -Id_simple_format ='[% (LevelName) s] [% (asctime) s]% (message) s' - + #define the end of the log output format - +Logfile_dir = Os.path.dirname (Os.path.abspath (__file__))#Directory of log files A atLogfile_name ='All2.log' #log file name - - #if the defined log directory does not exist, create a - if notOs.path.isdir (logfile_dir): - Os.mkdir (Logfile_dir) - in #full path of the log file -Logfile_path =Os.path.join (Logfile_dir, Logfile_name) to + #Log Configuration Dictionary -Logging_dic = { the 'version': 1, * 'disable_existing_loggers': False, $ 'formatters': {Panax Notoginseng ' Standard': { - 'format': Standard_format, the 'datefmt':'%y-%m-%d%h:%m:%s', + }, A ' Simple': { the 'format': Simple_format + }, - }, $ 'Filters': {}, $ 'handlers': { - 'Console': { - ' Level':'DEBUG', the 'class':'logging. Streamhandler',#Print to screen - 'Formatter':' Simple'Wuyi }, the 'default': { - ' Level':'DEBUG', Wu 'class':'Logging.handlers.RotatingFileHandler',#Save to file - 'filename': Logfile_path,#log File About 'MaxBytes': 1024*1024*5,#Log size 5M $ 'Backupcount': 5, - 'Formatter':' Standard', - 'encoding':'Utf-8',#log file encoding, no longer worry about the Chinese log garbled - }, A }, + 'Loggers': { the "': { - 'handlers': ['default','Console'],#This adds the two handler defined above, that is, the log data is written to the file and printed to the screen $ ' Level':'DEBUG', the 'Propagate': True,#upward (higher level of logger) pass the }, the }, the } -Logging.config.dictConfig (Logging_dic)#Import the configuration defined above inLogger = Logging.getlogger (__name__)#generate a log instance theLogger.info ('It works!')#record the running status of the file
To invoke the test file:
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 """4 mylogging Test5 """6 7 Import Time8 ImportLogging9 fromLog_demoImportMy_logging#Import a custom logging configurationTen OneLogger = Logging.getlogger (__file__)#Generating Logger instances A - - defdemo (): theLogger.debug ("start range ... time:{}". Format (Time.time ())) -Logger.info ("Chinese test begins ... ") - forIinchRange (10): -Logger.debug ("i:{}". Format (i)) +Time.sleep (2) - Else: +Logger.debug ("Over range ... time:{}". Format (Time.time ())) ALogger.info ("Chinese test finished ... ") at - if __name__=="__main__": -Demo ()
How the log of Python is handled