In the previous period, in order to add log function to the project, I think of the logging module, Baidu logging a big push, are all kinds of replication, and did not find their own desired results; My goal is simple: in the log to write files in the console output, more convenient debugging, I have the following code to satisfy this function:
1 #Coding=utf-82 3 ImportLogging4 Import Time5 ImportCommonparameter6 7 classLog:8 def __init__(self):9Self.logname = Commonparameter.log_path +'\\'+'Log'+time.strftime ('%y-%m-%d') +'. Log'Ten One defprintconsole (self, level, message): A #Create a logger -Logger = Logging.getlogger ('MyLogger') - Logger.setlevel (logging. DEBUG) the #create a handler to write to the log file -FH = logging. Filehandler (Self.logname,'a') - Fh.setlevel (logging. DEBUG) - #create another handler for output to the console +CH =logging. Streamhandler () - Ch.setlevel (logging. DEBUG) + #define the output format of the handler AFormatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') at Fh.setformatter (Formatter) - Ch.setformatter (Formatter) - #Add handler to logger - Logger.addhandler (FH) - logger.addhandler (CH) - #record a log in ifLevel = ='Info': - logger.info (message) to elifLevel = ='Debug': + logger.debug (message) - elifLevel = ='Warning': the logger.warning (message) * elifLevel = ='Error': $ logger.error (message)Panax Notoginseng logger.removehandler (CH) - Logger.removehandler (FH) the + defDebug (self,message): ASelf.printconsole ('Debug', message) the + definfo (self,message): -Self.printconsole ('Info', message) $ $ defWarning (self,message): -Self.printconsole ('Warning', message) - the deferror (Self,message): -Self.printconsole ('Error', message)Wuyi the if __name__=='__main__': -Log =Log () WuLog.info ('Info msg1000013333') -Log.debug ('Debug MSG') AboutLog.warning ('Warning MSG') $Log.error ('Error msg')
Ps:
Self.logname = Commonparameter.log_path + ' \ \ ' + ' log ' +time.strftime ('%y-%m-%d ') + '. Log ' #你存放日志的路径
Python+selenium in the UI Automation test project, Common Tips 4: Log printing, longging module (console and file simultaneous output)