Python Script Example:
1 ImportLogging.config2 #load the logging configuration file3Logging.config.fileConfig ("Logging_conf.ini")4 #get a logger named example5Logger = Logging.getlogger ("Example"# (If you create the name of the logger object simultaneous, it does not exist in the configuration file, it will inherit the root configuration)6 #print error message to file7Logger.debug (' Debug Info ')
Example configuration file:
1 [Loggers]#Configuring the Logger entity2 Keys=root,example#a root logger, a logger named example3 4 [Handlers]#Configuring Handler Entities5 Keys=consolehandler,rotatefilehandler#6 7 [formatters]#Configure format Entities8 keys=Simpleformatter9 [Formatter_simpleformatter]#format=[% (Asctime) s] (% (levelname) s)% (name) s:%(message) s[Logger_root]#Root LoggerLevel=debug#You must specify a level and a series of handlershandlers=Consolehandler,rotatefilehandler[Logger_example]#Recorder named ExampleLevel=debug#level is debug, log that is greater than or equal to the debug level is outputhandlers=Consolehandler,rotatefilehandlerQualname=example#the name that the application uses to get the loggerPropagate=0#whether it will be passed to a higher-level logger (whether to inherit the parent class)[Handler_consolehandler]#configuration of handlers for output to the console24class=StreamhandlerLevel=DEBUGFormatter=Simpleformatterargs=(Sys.stdout,)[Handler_rotatefilehandler]#handler configuration for output to file30class=handlers. RotatingfilehandlerLevel=DEBUGFormatter=SimpleformatterArgs= ('Log_error.log','a', 10000, 9)
configuration file format Description:
1. The approximate process is to create a logger instance--Create a handler instance and add it to the logger--Create an Fomatter instance, pass it as a parameter to the handler instance, specify the output format--the logger instance to find handler, and invoke the appropriate method.
So the main is to configure the use of the logger, the corresponding processing program, format.
2. The args parameter description in [Handler_rotatefilehandler]:
1) output the file name Log_error.log,
2) How to open the file, A represents an existing Log_error.log is automatically renamed to LOG_ERROR.LOG.L when the
3) file is added to the end of the file, and then a log_ is recreated. Error.log
4) the number of reserved files is 9, if the above log_error.log and more than 10k, will again rename Log_error.log to Log_ Error.log.1,
But because Log_error.log.1 already exists, first change the existing log_error.log.1 to Log_ Error.log.2.
And so on, when the last file name is log_error.log.9, and log_error.log again exceeds 10k,log_ Error.log.9 will be deleted.
Resources:
Https://docs.python.org/2.7/library/logging.config.html#module-logging.config
Https://www.jianshu.com/p/feb86c06c4f4
https://my.oschina.net/leejun2005/blog/126713
Python read configuration file print log