import os
import sys

import logbook
import logbook.more

class LogRecord(object):

    # 日志格式
    def logFormate(self,record, handler):
        formate = "[{date}] [{level}] [{filename}] [{func_name}] [{lineno}] {msg}".format(
            date=record.time,  # 日志时间
            level=record.level_name,  # 日志等级
            filename=os.path.split(record.filename)[-1],  # 文件名
            func_name=record.func_name,  # 函数名
            lineno=record.lineno,  # 行号
            msg=record.message  # 日志内容
        )
        return formate

    # 获取logger
    def getLogger(self,fileLogFlag=True, stdOutFlag=True):
        dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
        dirname = os.path.join(dirname, "logs")
        filename = filename.replace(".py", "") + ".log"
        if not os.path.exists(dirname):
            os.mkdir(dirname)

        logbook.set_datetime_format('local')
        logger = logbook.Logger(filename)
        logger.handlers = []

        if fileLogFlag:  # 日志输出到文件
            logFile = logbook.TimedRotatingFileHandler(os.path.join(dirname, filename), date_format='%Y-%m-%d',
                                                       bubble=True, encoding='utf-8')
            logFile.formatter = self.logFormate
            logger.handlers.append(logFile)

        if stdOutFlag:  # 日志打印到屏幕
            logStd = logbook.more.ColorizedStderrHandler(bubble=True)
            logStd.formatter = self.logFormate
            logger.handlers.append(logStd)
        return logger