def reinit_comlog(loggername, loglevel=logging.INFO, logfile='cup.log', logtype=ROTATION, maxlogsize=1073741824, bprint_console=False, gen_wf=False): # too many arg pylint: disable=R0913 """ reinitalize logging system, paramters same to init_comlog. reinit_comlog will reset all logging parameters, Make sure you used a different loggername from the old one! """ global G_INITED_LOGGER if loggername in G_INITED_LOGGER: msg = 'loggername:%s has been already initalized!!!' % loggername raise ValueError(msg) G_INITED_LOGGER.append(loggername) loggerman = _LoggerMan() loggerman._reset_logger(logging.getLogger(loggername)) if os.path.exists(logfile) is False: if platforms.is_linux(): os.mknod(logfile) else: with open(logfile, 'w+') as fhandle: fhandle.write('----Windows File Creation ----\n') elif os.path.isfile(logfile) is False: raise err.LoggerException( 'The log file exists. But it\'s not regular file') loggerman._config_filelogger(loglevel, logfile, logtype, maxlogsize, bprint_console, gen_wf) # too many arg pylint: disable=w0212 info('-' * 20 + 'Log Reinitialized Successfully' + '-' * 20) return
def reinit_comlog(loggername, loglevel=logging.INFO, logfile='cup.log', logtype=ROTATION, maxlogsize=1073741824, bprint_console=False, gen_wf=False): # too many arg pylint: disable=R0913 """ 重新设置comlog, 参与意义同init_comlog. reinit_comlog会重新设置整个进程的参数, 但请注意loggername一定不能与 原来的loggername相同,相同的loggername会raise ValueError """ global G_INITED_LOGGER if loggername in G_INITED_LOGGER: msg = 'loggername:%s has been already initalized!!!' % loggername raise ValueError(msg) G_INITED_LOGGER.append(loggername) loggerman = _LoggerMan() loggerman._reset_logger(logging.getLogger(loggername)) if os.path.exists(logfile) is False: if platforms.is_linux(): os.mknod(logfile) else: with open(logfile, 'w+') as fhandle: fhandle.write('----Windows File Creation ----\n') elif os.path.isfile(logfile) is False: raise err.LoggerException( 'The log file exists. But it\'s not regular file') loggerman._config_filelogger(loglevel, logfile, logtype, maxlogsize, bprint_console, gen_wf) # too many arg pylint: disable=w0212 info('-' * 20 + 'Log Reinitialized Successfully' + '-' * 20) return
def reinit_comlog(loggername, loglevel=logging.INFO, logfile='cup.log', logtype=ROTATION, maxlogsize=1073741824, bprint_console=False, gen_wf=False): """ reinitialize default root logger for cup logging :param loggername: logger name, should be different from the original one """ global G_INITED_LOGGER if loggername in G_INITED_LOGGER: msg = ('loggername:{0} has been already used!!! Change a name'.format( loggername)) raise ValueError(msg) G_INITED_LOGGER.append(loggername) tmplogger = logging.getLogger(loggername) if os.path.exists(logfile) is False: if platforms.is_linux(): os.mknod(logfile) else: with open(logfile, 'w+') as fhandle: fhandle.write('\n') elif os.path.isfile(logfile) is False: raise err.LoggerException( 'The log file exists. But it\'s not regular file' ) loggerman = _RootLogerMan() loggerparms = LoggerParams( loglevel, logfile, logtype, maxlogsize, bprint_console, gen_wf ) LogInitializer.setup_filelogger(tmplogger, loggerparms) loggerman.reset_rootlogger(tmplogger) info('-' * 20 + 'Log Reinitialized Successfully' + '-' * 20) return
def get_rootlogger(self): """ get default(root) logger """ if self._rootlogger is None: raise err.LoggerException( 'The Cup logger has not been initalized Yet. ' 'Call init_comlog first') return self._rootlogger
def setup_filelogger(cls, logger, logparams): """ config logger """ loglevel = logparams.loglevel strlogfile = logparams.logfile logtype = logparams.logtype maxsize = logparams.maxlogsize bprint_console = logparams.bprint_console gen_wf = logparams.gen_wf if not os.path.exists(strlogfile): try: if platforms.is_linux(): os.mknod(strlogfile) else: with open(strlogfile, 'w+') as fhandle: fhandle.write('\n') except IOError: raise err.LoggerException( 'logfile does not exist. ' 'try to create it. but file creation failed' ) logger.setLevel(loglevel) # '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(message)s' tznum = time.strftime('%z') tzkey = time.strftime('%Z') formatter = logging.Formatter( fmt='%(levelname)s:\t %(asctime)s {0}({1}) * ' '[%(process)d:%(thread)x] [%(filename)s:%(lineno)s] %(message)s' .format(tznum, tzkey) ) if bprint_console: info('bprint_console enabled, will print to stdout') streamhandler = logging.StreamHandler() streamhandler.setLevel(loglevel) streamhandler.setFormatter(formatter) logger.addHandler(streamhandler) fdhandler = None if logtype == ROTATION: fdhandler = handlers.RotatingFileHandler( strlogfile, 'a', maxsize, ROTATION_COUNTS, encoding='utf-8' ) else: fdhandler = logging.FileHandler( strlogfile, 'a', encoding='utf-8' ) fdhandler.setFormatter(formatter) fdhandler.setLevel(loglevel) if gen_wf: # add .wf handler file_wf = str(strlogfile) + '.wf' warn_handler = logging.FileHandler(file_wf, 'a', encoding='utf-8') warn_handler.setLevel(logging.WARNING) warn_handler.setFormatter(formatter) logger.addHandler(warn_handler) fdhandler.addFilter(_MsgFilter(logging.WARNING)) logger.addHandler(fdhandler)
def set_rootlogger(self, loggername, logger): """ set default(root) logger with a new loggername """ if self._rootlogger is not None: raise err.LoggerException( """WARNING!!! The cup logger has been initalized already\ .Plz do NOT init_comlog twice""") self._rootlogger = logger self._loggername = loggername
def _config_filelogger(self, loglevel, strlogfile, logtype, maxsize, bprint_console, gen_wf=False): # too many arg pylint: disable=R0913 if not os.path.exists(strlogfile): try: os.mknod(strlogfile) except IOError: raise err.LoggerException( 'logfile does not exist. ' 'try to create it. but file creation failed') self._logfile = strlogfile self._logtype = logtype self._pylogger.setLevel(loglevel) self._maxsize = maxsize # '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(message)s' formatter = logging.Formatter( '%(levelname)s: %(asctime)s * ' '[%(process)d:%(thread)d] [%(filename)s:%(lineno)s] %(message)s') if bprint_console: streamhandler = logging.StreamHandler() streamhandler.setLevel(loglevel) streamhandler.setFormatter(formatter) self._pylogger.addHandler(streamhandler) fdhandler = None if logtype == ROTATION: fdhandler = handlers.RotatingFileHandler(self._logfile, 'a', maxsize, ROTATION_COUNTS, encoding='utf-8') else: fdhandler = logging.FileHandler(self._logfile, 'a', encoding='utf-8') fdhandler.setFormatter(formatter) fdhandler.setLevel(loglevel) if gen_wf: # add .wf handler file_wf = str(self._logfile) + '.wf' warn_handler = logging.FileHandler(file_wf, 'a', encoding='utf-8') warn_handler.setLevel(logging.WARNING) warn_handler.setFormatter(formatter) self._pylogger.addHandler(warn_handler) fdhandler.addFilter(_MsgFilter(logging.WARNING)) self._pylogger.addHandler(fdhandler)
def init_comlog(loggername, loglevel=logging.INFO, logfile='cup.log', logtype=ROTATION, maxlogsize=1073741824, bprint_console=False, gen_wf=False): # too many arg pylint: disable=R0913 """ 初始化日志函数 :param loggername: 这个logger的名字 :param loglevel: 一共四种 log.DEBUG log.INFO log.ERROR log.CRITICAL :param logfile: log文件的位置,如不存在,会尝试创建该文件 :param logtype: 支持两种cup.log.ROTATION cup.log.INFINITE ROTATION会在文件大小达到maxlogsize的时候进行switch. 一共会switch 30个文件, 然后在这30个文件里面ROTATION的写 INFINITE会一直写log文件 :param maxlogsize: logfile的最大文件大小(单位byte).超过会进行覆盖写或者switch. :param b_printcmd: 打印日志到logfile的同时,是否打印到stdout. :param gen_wf: 将级别大于等于WARNING的消息打印到${logfile}.wf中. 请注意,打印日志时要么打印unicode字符,要么打印Python默认的UTF8的字符 *E.g.* :: import logging from cup import log log.init_comlog( 'test', log.DEBUG, '/home/work/test/test.log', log.ROTATION, 1024, False ) log.info('test xxx') log.critical('test critical') """ loggerman = _LoggerMan() if loggerman.is_initalized() is False: # loggerman._setlogger(logging.getLogger(loggername)) loggerman._setlogger(logging.getLogger()) if os.path.exists(logfile) is False: if platforms.is_linux(): os.mknod(logfile) else: with open(logfile, 'w+') as fhandle: fhandle.write('----Windows File Creation ----\n') elif os.path.isfile(logfile) is False: raise err.LoggerException( 'The log file exists. But it\'s not regular file') loggerman._config_filelogger(loglevel, logfile, logtype, maxlogsize, bprint_console, gen_wf) # too many arg pylint: disable=w0212 info('-' * 20 + 'Log Initialized Successfully' + '-' * 20) global G_INITED_LOGGER G_INITED_LOGGER.append(loggername) else: print '[%s:%s] init_comlog has been already initalized' % \ (_file(1), _line(1)) return
def _setlogger(self, logger): if self._pylogger is not None: raise err.LoggerException( """WARNING!!! The cup logger has been initalized already\ .Plz do NOT init_comlog twice""") self._pylogger = logger
def _getlogger(self): if self._pylogger is None: raise err.LoggerException( 'The Cup logger has not been initalized Yet. ' 'Call init_comlog first') return self._pylogger
def init_comlog(loggername, loglevel=logging.INFO, logfile='cup.log', logtype=ROTATION, maxlogsize=1073741824, bprint_console=False, gen_wf=False): """ Initialize your default logger :param loggername: Unique logger name for default logging. :param loglevel: 4 default levels: log.DEBUG log.INFO log.ERROR log.CRITICAL :param logfile: log file. Will try to create it if no existence :param logtype: Two type candidiates: log.ROTATION and log.INFINITE log.ROTATION will let logfile switch to a new one (30 files at most). When logger reaches the 30th logfile, will overwrite from the oldest to the most recent. log.INFINITE will write on the logfile infinitely :param maxlogsize: maxmum log size with byte :param b_printcmd: print to stdout or not? :param gen_wf: print log msges with level >= WARNING to file (${logfile}.wf) *E.g.* :: import logging from cup import log log.init_comlog( 'test', log.DEBUG, '/home/work/test/test.log', log.ROTATION, 1024, False ) log.info('test xxx') log.critical('test critical') """ loggerman = _RootLogerMan() rootloger = logging.getLogger() if not loggerman.is_initalized(): loggerman.set_rootlogger(loggername, rootloger) if os.path.exists(logfile) is False: if platforms.is_linux(): os.mknod(logfile) else: with open(logfile, 'w+') as fhandle: fhandle.write('\n') elif os.path.isfile(logfile) is False: raise err.LoggerException( 'The log file exists. But it\'s not regular file') loggerparams = LoggerParams(loglevel, logfile, logtype, maxlogsize, bprint_console, gen_wf) LogInitializer.setup_filelogger(rootloger, loggerparams) info('-' * 20 + 'Log Initialized Successfully' + '-' * 20) global G_INITED_LOGGER G_INITED_LOGGER.append(loggername) else: print('[{0}:{1}] init_comlog has been already initalized'.format( LogInitializer.get_codefile(1), LogInitializer.get_codeline(1))) return