Common modules
1 Logging Module
Log level: Noset (not set)
Debug---(debug information)----can also be expressed as 10
info--(Message information)----can also be expressed as 20
Warning---(warning message)----can also be expressed as 30
The error----------can also be expressed as 40
Critical---(Critical error)---can also be expressed as 50
Default level is warning, default print to Terminal
1 ImportLogging2 3Logging.debug ('Debugging Debug')4Logging.info ('Message Info')5Logging.warning ('warning Warn')6Logging.error ('Wrong Error')7Logging.critical ('Severe critical')8 9 " "Ten warning:root: Warning Warn One error:root: Wrong error A critical:root: Severe CRITICAL - " "
2,logging Module Global configuration, valid for all logger
Four objects of the logging module:
Logger: The object that produces the log filter: the object that filters the log (not commonly used, can be ignored) Handler: accepts the log and then controls the print to a different place, Filehandler is used to print to the file, Streamhandler is used to print to the Terminal formatter object: You can customize different log format objects and then bind to different handler objects to control the different handler log formats
Configuration parameters:
FileName: Creates a filedhandler with the specified file name so that the log is stored in the file
FileMode: File open mode, use this parameter when filename is specified, default value is ' A ', can also be specified as ' W '
Format: Specifies the log display format used by handler
DATAFMT: Specify DateTime format
Level: Set the log levels for Rootlogger
Stream: Create Streamhandler with the specified stream, you can specify output to Sys.stderr,sys.stdout or file, default to Sys.stderr. If you list both the filename and stream two arguments, the stream parameter is ignored
Format:
%(name) S:logger name, not username, detailed view %(levelno) S: Log level in digital form %(levelname) S: Log level in text form %( Pathname) S: The full pathname of the module that called the log output function, may not have %(filename) s: The file name of the module that called the log output function %(module) s: called the block name of the log output function (funcName) S: function name of the call log output function %(Lineno) d: The code line where the statement that called the log output function is located (created) F: Current time, represented by the UNIX standard floating-point number representing the time %(relativecreated) d: When the log information is output, the number of milliseconds since logger was created (asctime) s: The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by the millisecond %(thread) d: Thread ID. There may not be a%(threadname) s: the thread name. There may not be a%(process) d: Process ID. May not have % (message) s: User-output messages
Levels of logger and handler
Logger is the first level of filtering, and then to handler, we can give logger and handler at the same time, but the main need is:
cannot be filtered by logger level, the log will not print;
cannot be filtered by handler level and the log will not print
Only logs filtered by logger level, and handler level can be printed
Well-defined logging profile (can be used elsewhere after modifying the relevant information)
1 """2 Logging Configuration3 """4 5 ImportOS6 ImportLogging.config7 8 #define three types of log output formats to start with9 TenStandard_format ='[% (asctime) s] [% (ThreadName) s:% (thread) d][task_id:% (name) s][% (filename) s:% (Lineno) d]' One '[% (LevelName) s] [% (message) s]' #where name is the name specified by GetLogger A -Simple_format ='[% (LevelName) s] [% (asctime) s][% (filename) s:% (Lineno) d]% (message) s' - theId_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 - +Logfile_name ='All2.log' #log file name A at #if the defined log directory does not exist, create a - if notOs.path.isdir (logfile_dir): - Os.mkdir (Logfile_dir) - - #full path of the log file -Logfile_path =Os.path.join (Logfile_dir, Logfile_name) in - #Log Configuration Dictionary toLogging_dic = { + 'version': 1, - 'disable_existing_loggers': False, the 'formatters': { * ' Standard': { $ 'format': Standard_formatPanax Notoginseng }, - ' Simple': { the 'format': Simple_format + }, A }, the 'Filters': {}, + 'handlers': { - #Print to the terminal's log $ 'Console': { $ ' Level':'DEBUG', - 'class':'logging. Streamhandler',#Print to screen - 'Formatter':' Simple' the }, - #Print to file log, collect info and above logsWuyi 'default': { the ' Level':'DEBUG', - 'class':'Logging.handlers.RotatingFileHandler',#Save to file Wu 'Formatter':' Standard', - 'filename': Logfile_path,#log File About 'MaxBytes': 1024*1024*5,#Log size 5M $ 'Backupcount': 5, - 'encoding':'Utf-8',#log file encoding, no longer worry about the Chinese log garbled - }, - }, A 'Loggers': { + #Logging.getlogger (__name__) Get the logger configuration 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 } - in the defload_my_logging_cfg (): theLogging.config.dictConfig (Logging_dic)#Import the logging configuration defined above AboutLogger = Logging.getlogger (__name__)#generate a log instance theLogger.info ('It works!')#record the running status of the file the the if __name__=='__main__': + load_my_logging_cfg () - theLogging configuration file
Attention:
Logger dictionary defines the reason for an empty key:
1 2 #Our solution is to define an empty key3 'Loggers': {4 "': {5 'handlers': ['default','Console'], 6 ' Level':'DEBUG',7 'Propagate': True,8 },9 Ten } One A so that when we take the Logger object again, -Logging.getlogger (__name__), different files __name__ different, this ensures that the print log when the identification information is different, but take the name to loggers to find the key name, but found that can not find, so the default use of key="'The configuration
Python Road--day15--modules logging module