Reference: http://www.jb51.net/article/42626.htm
Reference: http://blog.csdn.net/u011541946/article/details/70198676
Describes how to write a Python log class for outputting different levels of log information to a log file in a local folder. We need to keep track of what our test scripts are doing, and the best way to do this is to write event monitoring. This event monitoring, for us now, still a little complex to understand, so I here, choose to encapsulate a simple log class, the same effect.
We probably need the following log output effect:
Problem Analysis:
We need to encapsulate a simple log class that has the following main content:
1. The log file format generated is the day of the month and seconds. Log
2. The generated xxx.log file is stored under the project root directory under the Logs folder
3. This log class, support Info,error two kinds of log level
4. Log output per line, e.g. time date + execution class name + log level + log description
Problem-Solving ideas:
1. In the root directory, create a new logs folder, how to get the relative path of this log, described earlier.
2. Log save name, need system time, before also introduced time formatted output
3. Python has a logging module to support our custom encapsulation of a new log class.
4. In the script, initialize an instance object of the log class, and then control the output info or error log information.
If you want to develop a log system, you need to output the log to the console and write to the log file, as long as you use:
1 #_*_ coding:utf-8 _*_2 ImportLogging3 ImportOs.path4 Import Time5 6 7 classLogger (object):8 def __init__(self, logger):9 """Ten Specify the file path to save the log, the log level, and the calling file One depositing a log in a specified file A :p Aram Logger: - """ - #Create a logger theSelf.logger =Logging.getlogger (Logger) - Self.logger.setLevel (logging. DEBUG) - - #Create a journal name. +RQ = Time.strftime ('%y%m%d%h%m', Time.localtime (Time.time ())) - #OS.GETCWD () Gets the path to the current file, Os.path.dirname () Gets the ancestor path of the specified file path +Log_path = Os.path.dirname (OS.GETCWD ()) +'/logs/' ALog_name = Log_path + RQ +'. Log' at #create a handler to write to the log file -FH =logging. Filehandler (Log_name) - fh.setlevel (logging.info) - - #create another handler for output to the console -CH =logging. Streamhandler () in ch.setlevel (logging.info) - to #define the output format of the handler +Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') - Fh.setformatter (Formatter) the Ch.setformatter (Formatter) * $ #Add handler to loggerPanax Notoginseng Self.logger.addHandler (FH) - self.logger.addHandler (CH) the + defGetlog (self): A returnSelf.logger
Python's custom encapsulates a simple log class