log.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:snmpsim 作者: etingof 项目源码 文件源码
def init(self, *priv):
        if not priv:
            raise error.SnmpsimError('Bad log file params, need filename')
        if sys.platform[:3] == 'win':
            # fix possibly corrupted absolute windows path
            if len(priv[0]) == 1 and priv[0].isalpha() and len(priv) > 1:
                priv = [priv[0] + ':' + priv[1]] + list(priv[2:])

        maxsize = 0
        maxage = None
        if len(priv) > 1 and priv[1]:
            localtime = time.localtime()
            if priv[1][-1] in ('k', 'K'):
                maxsize = int(priv[1][:-1]) * 1024
            elif priv[1][-1] in ('m', 'M'):
                maxsize = int(priv[1][:-1]) * 1024 * 1024
            elif priv[1][-1] in ('g', 'G'):
                maxsize = int(priv[1][:-1]) * 1024 * 1024 * 1024
            elif priv[1][-1] in ('h', 'H'):
                maxage = ('H', int(priv[1][:-1]))
            elif priv[1][-1] in ('d', 'D'):
                maxage = ('D', int(priv[1][:-1]))
            else:
                raise error.SnmpsimError(
                    'Unknown log rotation criteria %s, use <NNN>K,M,G for size or <NNN>H,D for time limits' % priv[1]
                )

        try:
            if maxsize:
                handler = handlers.RotatingFileHandler(priv[0], backupCount=30, maxBytes=maxsize)
            elif maxage:
                handler = handlers.TimedRotatingFileHandler(priv[0], backupCount=30, when=maxage[0], interval=maxage[1])
            else:
                handler = handlers.WatchedFileHandler(priv[0])

        except AttributeError:
            raise error.SnmpsimError(
                'Bad log rotation criteria: %s' % sys.exc_info()[1]
            )

        handler.setFormatter(logging.Formatter('%(asctime)s %(name)s: %(message)s'))
        self._logger.addHandler(handler)

        self('Log file %s, rotation rules: %s' % (
        priv[0], maxsize and '> %sKB' % (maxsize / 1024) or maxage and '%s%s' % (maxage[1], maxage[0]) or '<none>'))
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号