#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")

写图片描述

这里写图片描述

Python3自定义日志类 mylog的更多相关文章

  1. Python3自定义日志类教程

    一.说明 Python3的logging功能是比较丰富的支持不同层次的日志输出,但或是我们想在日志前输出时间.或是我们想要将日志输入到文件,我们还是想要自定义日志类. 之前自己也尝试写过但感觉文档太乱 ...

  2. flask中自定义日志类

    一:项目架构 二:自定义日志类 1. 建立log.conf的配置文件 log.conf [log] LOG_PATH = /log/ LOG_NAME = info.log 2. 定义日志类 LogC ...

  3. c#自定义日志记录

    废话不多说,直接上代码: 很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可. 默认保存在:项目/temp/log /// <summary> /// 日志类 /// & ...

  4. 《手把手教你》系列基础篇(八十五)-java+ selenium自动化测试-框架设计基础-TestNG自定义日志-下篇(详解教程)

    1.简介 TestNG为日志记录和报告提供的不同选项.现在,宏哥讲解分享如何开始使用它们.首先,我们将编写一个示例程序,在该程序中我们将使用 ITestListener方法进行日志记录. 2.Test ...

  5. python3+selenium框架设计03-封装日志类

    首先我们先来实现日志的功能,日志可以使用python3自带logging模块,不会的可以百度一下相关文章,也可以看我另外一篇文章Python3学习笔记24-logging模块 在封装日志类前,我们需要 ...

  6. python3+requests库框架设计02-封装日志类

    首先我们先来实现日志的功能,日志可以使用python3自带logging模块,不会的可以百度一下相关文章,也可以看我另外一篇文章Python3学习笔记24-logging模块 在封装日志类前,我们需要 ...

  7. python3.4中自定义数组类(即重写数组类)

    '''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能''' class MyArray: '''保证输入值为数字元素(整型,浮点型,复数)''' de ...

  8. python3 配置logging日志类

    配置类config_file: from configparser import ConfigParser class config_file: def __init__(self,conf_file ...

  9. YII2 自定义日志路径

    YII 提供的日志写入方法: 1.Yii::getLogger()->log($message, $level, $category = 'application') 2.Yii::trace( ...

随机推荐

  1. Redis入门到高可用(五)—— 单线程

    一.单线程为何这么快 1)绝大部分请求是纯粹的内存操作(非常快速) 2)采用单线程,避免了不必要的上下文切换和竞争条件 3)非阻塞IO 内部实现采用epoll,采用了epoll+自己实现的简单的事件框 ...

  2. wechat-注意事项

  3. 24-Python3 OS

    24-Python3 OS ''' OS文件/目录方法 ''' ##os.access():检验权限模式 fo1 = open('/Users/ligaijiang/PycharmProjects/f ...

  4. websocket协议的思考

    同过wireshark抓包,都是TCP的连接,省了好多的HTTP的头部请求 Ping Pong,TCP keep alive,双方没有数据来往的时候,通过发空白报文,侦测的报文来决定看这个链接是否还存 ...

  5. Hinge Loss、交叉熵损失、平方损失、指数损失、对数损失、0-1损失、绝对值损失

    损失函数(Loss function)是用来估量你模型的预测值 f(x) 与真实值 Y 的不一致程度,它是一个非负实值函数,通常用 L(Y,f(x)) 来表示.损失函数越小,模型的鲁棒性就越好. 损失 ...

  6. (转载)常用正则表达式大全!(例如:匹配中文、匹配html)

    正则匹配java注意点: 如果加 ^[\n]* 表示替换遇到 \n 的前后内容,如果加[\n]表示替换\n本处内容 原文地址:http://blog.csdn.net/dl020840504/arti ...

  7. python中参数传递之位置传递、关键字传递、包裹传递与解包裹

    原文地址https://blog.csdn.net/love666666shen/article/details/77131487 1.位置与关键字传递 (1)位置传递:先用形式参数定义,然后在调用时 ...

  8. iOS UI布局-回到顶部

    回到顶部,是比较常用的一个效果 核心代码 在ViewDidLoad中,添加回到顶部按钮 计算偏移量,如果当前显示的内容全部向上隐藏掉,则显示“回到顶部”按钮 // // ViewController. ...

  9. vsftp

    [安装vsftpd]安装vsftpd工具步骤   1 安装vsftpd组件 [root@bogon ~]# yum -y install vsftpd 安装完后,有/etc/vsftpd/vsftpd ...

  10. 记在Archlinux中安装python的pymssql模块过程中遇到的问题

    为什么要安装这个模块?因为要连接SQLServer数据库. 看到可以使用pyodbc这个模块进行连接,但对odbc不熟悉,所以选用了看起来更简单的 pymssql. 直接执行: pip install ...