Python3自定义日志类 mylog

#encoding=utf-8

import os, sys
import datetime
import time


class Mylog(object):

    # 根文件夹
    root_dir = sys.path[0]
    # 根目录
    root_path = sys.path[0] + os.path.sep
    # 系统目录分割线
    sys_sep = os.path.sep
    # 配置
    option = {
        # 日志级别:  0:全部,1:调试,2:警告,3:错误
        'level': 0,
        # 是否开启,如果关闭则不输出也不记录日志
        'is_open': True,
        # 是否print输出
        'is_print': True,
        # 是否记录到日志文件
        'is_write': True,
        # 是否在每条日志内容前面加前缀
        'is_prefix': True,
        # 如果开启了每条日志前加前缀,设置日志级别为1的前缀
        'level_1_prefix': 'Test: ',
        # 如果开启了每条日志前加前缀,设置日志级别为2的前缀
        'level_2_prefix': 'Warning: ',
        # 如果开启了每条日志前加前缀,设置日志级别为3的前缀
        'level_3_prefix': 'Error: ',
        # 存放日志文件的根文件夹名称
        'root_dir_name': 'mylog',
        # 自定义存放日志文件的文件名称,此文件夹是在 root_dir_name 文件夹下
        'dir_name': ''
    }

    def __init__(self, config=None):
        if config is not None:
            self.option.update(dict(config))

        # 日志保存的文件夹(全路径)
        save_dir = self.root_path + self.option['root_dir_name']

        # 创建文件夹
        if os.path.isdir(save_dir) is not True:
            os.mkdir(save_dir)
        if len(self.option['dir_name']) > 0:
            save_dir += self.sys_sep + self.option['dir_name']
            if os.path.isdir(save_dir) is not True:
                os.mkdir(save_dir)

        self.save_dir = save_dir
        self.save_path = save_dir + self.sys_sep

    '''
    输入日志/记录日志
    '''
    def log(self, content='', level=0):
        self._print_log(content, level)
        self._write_log(content, level)

    '''
    输入日志
    '''
    def _print_log(self, content, level):
        if self.option['is_open'] is True and self.option['is_print'] is True:
            if self.option['level'] == 0 or self.option['level'] == level:
                if level > 0:
                    content = self.option['level_' + str(level) + '_prefix'] + content
                print(content)

    '''
    记录日志
    '''
    def _write_log(self, content, level):
        if self.option['is_open'] is True and self.option['is_print'] is True:
            if self.option['level'] == 0 or self.option['level'] == level:
                if self.option['is_prefix'] is True:
                    today = datetime.date.today()
                    file_name = str(today) + '.log'
                    now = time.strftime("%H:%M:%S")
                    log_file = self.save_path + file_name
                    if level > 0:
                        content = self.option['level_' + str(level) + '_prefix'] + content
                    if os.path.isfile(log_file):
                        save_file = open(log_file, 'a')
                    else:
                        save_file = open(log_file, 'w')
                    save_file.write(str(now) + "\r\n" + content + "\r\n")
                    save_file.close()

 

**重点内容
#!/usr/bin/env python
#-*- coding: GBK -*-
__author__ = 'DiaoHuabin'

import logging
import getpass
import sys

#定义MyLog类
class MyLog(object):
    '''这个类用于创建一个自用的log'''
    def __init__(self):  #类MyLog的构造函数
        user = getpass.getuser()  #返回用户的登录名
        self.logger = logging.getLogger(user)  #返回一个特定名字的日志
        self.logger.setLevel(logging.DEBUG)   #对显示的日志信息设置一个阈值低于DEBUG级别的不显示
        logFile = './'+sys.argv[1][0:-3] + '.log'  # 日志文件名
        formatter = logging.Formatter('%(asctime)-12s $(levelname)-8s %(name)-10s %(message)-12s')

        '''日志显示到屏幕上并输出到日志文件内'''
        logHand = logging.FileHandler(logFile)  #输出日志文件,文件名是logFile
        logHand.setFormatter(formatter)  #为logHand以formatter设置格式
        logHand.setLevel(logging.ERROR) #只有错误才被记录到logfile中

        logHandSt = logging.StreamHandler() #class logging.StreamHandler(stream=None)
        # 返回StreamHandler类的实例,如果stream被确定,使用该stream作为日志输出,反之,使用
        #sys.stderr
        logHandSt.setFormatter(formatter) #为logHandSt以formatter设置格式

        self.logger.addHandler(logHand) #添加特定的handler logHand到日志文件logger中
        self.logger.addHandler(logHandSt) #添加特定的handler logHandSt到日志文件logger中

        '''日志的5个级别对应以下的五个函数'''
    def debug(self,msg):
        self.logger.debug(msg)  #Logs a message with level DEBUG on this logger.
        # The msg is the message format string

    def info(self,msg):
        self.logger.info(msg)

    def warn(self,msg):
        self.logger.warn(msg)

    def error(self,msg):
        self.logger.error(msg)

    def critical(self,msg):
        self.logger.critical(msg)

if __name__ == '__main__':
    mylogw = MyLog()
    mylogw.debug("I'm debug")
    mylogw.info("I'm info")
    mylogw.warn("I'm warn")
    mylogw.error("I'm error")
    mylogw.critical("I'm critical")


写图片描述

 


这里写图片描述

posted @ 2019-01-03 10:28  konglingbin  阅读(1783)  评论(0编辑  收藏  举报