python工具类两则:读取properties,自动记录行数的LogManager

来源:互联网 发布:民国算法 编辑:程序博客网 时间:2024/06/04 01:29

测试类

from PropertiesUtil import PropertiesUtil  dictProperties = PropertiesUtil().getProperties()  print dictProperties  

工具类

# -*- coding: utf-8 -*-import sysimport osreload(sys)sys.setdefaultencoding('utf8')'''自动加载pythonSripts/目录下的properties'''class PropertiesUtil(object):    __instance = None    def __init__(self):        pass    # singleton Dao必须是新式类,即声明时加上object Dao(object)    def __new__(cls, *args, **kwargs):        if not cls.__instance:            cls.__instance = super(cls.__class__, cls).__new__(                cls, *args, **kwargs)            cls.__instance.properties = {}            cls.__instance.__loadProperties()        print '[%s] the address of this instance in Memory: ' % (cls.__name__), id(cls.__instance)        return cls.__instance    def __loadProperties(self):        print "PropertiesUtil().__loadProperties..."        pythonAppRootPath = os.path.abspath(os.path.join(os.path.dirname(__file__),"."))        for strFile in os.listdir(pythonAppRootPath):            if strFile.endswith('.properties'):                strAbsPropertiesPath = os.path.abspath(os.path.join( pythonAppRootPath, strFile))                print strAbsPropertiesPath                try:                    pro_file = open(strAbsPropertiesPath, 'Ur')                    for line in pro_file.readlines():                        line = line.strip().replace('\n', '')                        if line.find("#") != -1:                            line = line[0:line.find('#')]                        if line.find('=') > 0:                            strs = line.split('=')                            self.properties[strs[0]]=strs[1]                except Exception, e:                    raise e                finally:                    pro_file.close()    def getProperties(self):        return self.propertiesif __name__ == '__main__':    print PropertiesUtil().getProperties()

LogManager

# -*- coding: utf-8 -*-# 配置日志信息import logging  import logging.config      import sysimport osclass MyLogger(object):      __instance = None    def __init__(self):            pass    # singleton Dao必须是新式类,即声明时加上object Dao(object)    def __new__(cls, *args, **kwargs):        if not cls.__instance:            cls.__instance = super(cls.__class__, cls).__new__(cls, *args, **kwargs)            working_path = os.path.abspath(os.path.dirname(__file__))            print("\n------------MyLogger\n",working_path)            CONF_LOG = working_path + os.path.sep + "logging.conf"              print ("logger properties file path: " + CONF_LOG)            logging.config.fileConfig(CONF_LOG);            cls.__instance.myLogger = logging.getLogger('myLogger')        print ('[%s] the address of this instance in Memory: '%(cls.__name__), id(cls.__instance))        return cls.__instance    def error(self, message):        callerFileName = sys._getframe().f_back.f_code.co_filename        callerLineNumber = sys._getframe().f_back.f_lineno          self.myLogger.error("%s: %04d >> %s"%(callerFileName, callerLineNumber, message))    def info(self, message):        callerFileName = sys._getframe().f_back.f_code.co_filename        callerLineNumber = sys._getframe().f_back.f_lineno          self.myLogger.info("%s: %04d >> %s"%(callerFileName, callerLineNumber, message))if __name__ == "__main__":      myLogger = MyLogger()    myLogger.error("s")    myLogger.info("sd")

配置文件 logging.conf

[loggers]keys=root,myLogger[handlers]keys=consoleHandler,infoRotatingFileHandler,errorRotatingFileHandler[formatters]keys=simpleFormatter[logger_root]level=DEBUGhandlers=consoleHandler[logger_myLogger]handlers=consoleHandler,infoRotatingFileHandler,errorRotatingFileHandlerqualname=myLoggerpropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[handler_infoRotatingFileHandler]  class=handlers.RotatingFileHandler  level=INFOformatter=simpleFormatter args=("/wls/apache/applogs/Pagi_qer/python_info.log", "a", 20*1024*1024, 10) #args=("d:/wls/apache/applogs/Pagi_qer/python_info.log", "a", 20*1024*1024, 10) [handler_errorRotatingFileHandler]  class=handlers.RotatingFileHandler  level=ERRORformatter=simpleFormatter args=("/wls/apache/applogs/Pagi_qer/python_error.log", "a", 20*1024*1024, 10)  [formatter_simpleFormatter]format=%(asctime)s %(levelname)-5s | %(message)sdatefmt=%Y-%m-%d %I:%M:%S
原创粉丝点击