Python面向对象编程11 日志文件

日志:系统运行过程中的记录(系统日志、用户日志、运行日志、错误日志)

import os
import logging

cerrunt_path = os.path.dirname(__file__)
log_path = cerrunt_path + '/../logs/test.log'

logger = logging.getLogger(__name__)    #创建日志对象
logger.setLevel(level=logging.INFO)     #设置日志级别
console = logging.StreamHandler()       #创建一个控制台日志输出对象
logger.addHandler(console)              #日志对象配置再控制台输出
formatter = logging.Formatter('[%(asctime)s]-[%(name)s]-[%(levelname)s]:%(message)s')
console.setLevel(level=logging.DEBUG)   #自定义日志级别

file_log = logging.FileHandler(log_path)
formatter1 = logging.Formatter('[%(asctime)s]-[%(name)s]-[%(levelname)s]:%(message)s')
logger.addHandler(file_log)
file_log.setFormatter(formatter1)

console.setFormatter(formatter)
logger.info('hello,word')

日志封装成类:

import datetime
import os
import logging
import time
import colorlog

cerrunt_time = time.strftime('%Y_%m_%d',time.gmtime())
cerrunt_path = os.path.dirname(__file__)
log_path = cerrunt_path + '/../logs/test_'+cerrunt_time+'.log'
logger = logging.getLogger(__name__)
log_colors_config = {
            'DEBUG': 'white',
            'INFO': 'white',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        }

class LogUtils:
    def __init__(self,logfile_path=log_path):
        self.logfile_path = logfile_path

    def print_file_log(self,level,message):

        file_log = logging.FileHandler(log_path)
        logger.setLevel(level=logging.DEBUG)
        formatter = logging.Formatter(
                fmt='[%(asctime)s.%(msecs)03d] %(filename)s:%(lineno)d [%(levelname)s]: %(message)s',
                datefmt='%Y-%m-%d  %H:%M:%S')
        formatter_color = colorlog.ColoredFormatter(
            fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s:%(lineno)d [%(levelname)s]: %(message)s',
            datefmt='%Y-%m-%d  %H:%M:%S',
            log_colors=log_colors_config)
        file_log.setFormatter(formatter)

        console = logging.StreamHandler()
        console.setLevel(level=logging.DEBUG)
        console.setFormatter(formatter_color)
        logger.addHandler(file_log)
        logger.addHandler(console)

        if level == 'info':
            logger.info(message)
        elif level == 'debug':
            logger.debug(message)
        elif level == 'warning':
            logger.warning(message)
        elif level == 'error':
            logger.error(message)
        logger.removeHandler(file_log)
        logger.removeHandler(console)
        file_log.close()
        console.close()

    def info(self,message):
        self.print_file_log(message)

    def debug(self,message):
        self.print_file_log(message)

    def waring(self,message):
        self.print_file_log(message)

    def error(self, message):
        self.print_file_log(message)

if __name__ == '__main__':
    log_utils = LogUtils()
    log_utils.print_file_log('debug', 'newdream  debug')
    log_utils.print_file_log('info', 'newdream  info')
    log_utils.print_file_log('warning', 'newdream  warning')
    log_utils.print_file_log('error', 'newdream  error')
    print(cerrunt_time)

日志应用:
demo.调用上面的自定义日志封装类

import os
import xlrd
import time
from xlrd.compdoc import CompDoc
from xlrd.biffh import XLRDError
from case_info import CaseInfo
from log_utils import LogUtils

logger = LogUtils()
class ExcelDataInof:
    def __init__(self,file_path):
        self.file_path = file_path

    def read_data_in_class(self):

        all_case_info = []
        try:
            excel_file = xlrd.open_workbook(self.file_path)
            logger.print_file_log('info','创建workbook对象成功')
        except FileNotFoundError as e:
            cerrunt_path = os.path.dirname(__file__)
            print(cerrunt_path)
            file_path = cerrunt_path + '/../test_case/test_case.xls'
            excel_file = xlrd.open_workbook(file_path)
            logger.print_file_log('error', str(e))
            # log_op.error('error',str(e))
        sheet = excel_file.sheet_by_index(0)
        for i in range(1,sheet.nrows):
            case_info = CaseInfo(sheet.cell_value(i,0),
                                  sheet.cell_value(i,1),
                                  sheet.cell_value(i,2),
                                  sheet.cell_value(i,3),
                                  sheet.cell_value(i,4),
                                  sheet.cell_value(i,5),
                                  sheet.cell_value(i,6),
                                  sheet.cell_value(i,7))
            all_case_info.append(case_info)

        return  all_case_info

if __name__ == '__main__':
    cerrunt_path = os.path.dirname(__file__)
    file_path = cerrunt_path + '/../test_case/test_ca2se.xls'
    Excel_data = ExcelDataInof(file_path)
    str1 = Excel_data.read_data_in_class()
    print(str1[0].act_results)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值