• python习题:生成日志文件


    import logging

    from logging import handlers
    class Logger(object):
        level_relations = {
            'debug':logging.DEBUG,
            'info':logging.INFO,
            'warning':logging.WARN,
            'error':logging.ERROR,
            'crit':logging.CRITICAL
        }#日志级别关系映射
        def __init__(self,fp,level='debug',when='midnight',interval=1,backCount=5,encoding='utf-8'):
            '''
     
            :param fp:日志文件路径
            :param level: 日志级别 默认是debug
            :param when: 分割日志的单位 S 秒、M 分、 H 小时、 D 天、 W 每星期(interval==0时代表星期一)、midnight 每天凌晨
            :param interval: 时间间隔 默认每天凌晨
            :param backCount: 备份文件个数 默认5个
            :param encoding: 日志文件编码
            '''
            self.level = self.level_relations.get(level)
            self.logger = logging.getLogger(fp)
            self.logger.setLevel(self.level)
            fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
            sh = logging.StreamHandler()
            sh.setFormatter(fmt)
            sh.setLevel(self.level)
            th = handlers.TimedRotatingFileHandler(fp,when=when,interval=interval,backupCount=backCount,encoding=encoding)
            th.setFormatter(fmt)
            th.setLevel(self.level)
            self.logger.addHandler(th)
            self.logger.addHandler(sh)
        def debug(self,msg):
            self.logger.debug(msg)
        def info(self,msg):
            self.logger.info(msg)
        def warning(self,msg):
            self.logger.warning(msg)
        def error(self,msg):
            self.logger.error(msg)
        def crit(self,msg):
            self.logger.critical(msg)
    if __name__ == '__main__':
        l = Logger('a.log')#实例化
        l.info('hehehe')#调用
  • 相关阅读:
    python -- 初始函数 函数的定义,函数的返回值以及函数的参数
    python 文件操作: 文件操作的函数, 模式及常用操作.
    第三节 深入JavaScript
    第二节 JavaScript基础
    第一节 JavaScript概述
    面试大纲
    flask
    面试准备
    数据结构与算法 学习
    Linux学习
  • 原文地址:https://www.cnblogs.com/blackbird0423/p/8488120.html
Copyright © 2020-2023  润新知