python 以单例模式封装logging相关api实现日志打印类

 

by:授客QQ1033553122

测试环境:

Python版本:Python 2.7

 

实现功能:

支持自由配置,如下log.conf,

1)可以配置日志文件路径(log_file);

2)按日志数量配置(backup_count)及单个日志文件的大小(max_bytes_each),自动化循环切换日志文件;

3)支持日志格式自定义(fmt);

4)支持日志记录器名称自定义(logger_name)

6)支持控制台日志和文件日志

5) 支持控制台日志级别自定义(log_level_in_console)

6)支持文件日志级别自定义(log_level_in_logfile)

7) 支持控制台和文件日志的各自的开启和关闭(分别为console_log_on, logfile_log_on)

log.conf配置文件

./config/logconfig.conf配置如下:

[LOGGING]

log_file = d:/testlog.txt

max_bytes_each = 3

backup_count = 5

fmt = |(asctime)s |(filename)s[line: |(lineno)d] |(levelname)s: |(message)s

logger_name = test_logger

log_level_in_console = 20

log_level_in_logfile = 10

console_log_on = 1

logfile_log_on = 1

#日志级别:CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0

#console_log_on  = 1 开启控制台日志,logfile_log_on = 1 开启文件日志

实践代码

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

 

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

 

__author__ = 'shouke'

import logging

from logging.handlers import RotatingFileHandler

import threading

import configparser

 

class LogSignleton(object):

    def __init__(self, log_config):

        pass

 

    def __new__(cls, log_config):

        mutex=threading.Lock()

        mutex.acquire() # 上锁,防止多线程下出问题

        if not hasattr(cls, 'instance'):

            cls.instance = super(LogSignleton, cls).__new__(cls)

            config = configparser.ConfigParser()

            config.read(log_config)

            cls.instance.log_filename = config.get('LOGGING', 'log_file')

            cls.instance.max_bytes_each = int(config.get('LOGGING', 'max_bytes_each'))

            cls.instance.backup_count = int(config.get('LOGGING', 'backup_count'))

            cls.instance.fmt = config.get('LOGGING', 'fmt')

            cls.instance.log_level_in_console = int(config.get('LOGGING', 'log_level_in_console'))

            cls.instance.log_level_in_logfile = int(config.get('LOGGING', 'log_level_in_logfile'))

            cls.instance.logger_name = config.get('LOGGING', 'logger_name')

            cls.instance.console_log_on = int(config.get('LOGGING', 'console_log_on'))

            cls.instance.logfile_log_on = int(config.get('LOGGING', 'logfile_log_on'))

            cls.instance.logger = logging.getLogger(cls.instance.logger_name)

            cls.instance.__config_logger()

        mutex.release()

        return cls.instance

 

    def get_logger(self):

        return  self.logger

 

    def __config_logger(self):

        # 设置日志格式

        fmt = self.fmt.replace('|','%')

        formatter = logging.Formatter(fmt)

 

        if self.console_log_on == 1: # 如果开启控制台日志

            console = logging.StreamHandler()

            #console.setLevel(self.log_level_in_console)

            console.setFormatter(formatter)

            self.logger.addHandler(console)

            self.logger.setLevel(self.log_level_in_console)

 

        if self.logfile_log_on == 1: # 如果开启文件日志

            rt_file_handler = RotatingFileHandler(self.log_filename, maxBytes=self.max_bytes_each, backupCount=self.backup_count)

            rt_file_handler.setFormatter(formatter)

            self.logger.addHandler(rt_file_handler)

            self.logger.setLevel(self.log_level_in_logfile)

 

if __name__ == '__main__':

    logsignleton = LogSignleton('./config/logconfig.conf')

    logger = logsignleton.get_logger()

    #logger = logging.getLogger('test_logger') # 在其它模块中时,可这样获取该日志实例

    logger.debug('this is a debug level message')

    logger.info('this is info level message')

    logger.warning('this is warning level message')

    logger.error('this is error level message')

    logger.critical('this is critical level message')

 

注:多次使用相同的name调用getLogger方法返回同一个logger对象,可通过id(obj)进行验证

运行结果:

d:\\目录下生成文件如下:

python 以单例模式封装logging相关api实现日志打印类的更多相关文章

  1. Python面向对象04 /封装、多态、鸭子类型、类的约束、super

    Python面向对象04 /封装.多态.鸭子类型.类的约束.super 目录 Python面向对象04 /封装.多态.鸭子类型.类的约束.super 1. 封装 2. 多态 3. 鸭子类型 4. 类的 ...

  2. C# 中通过API实现的打印类

    using System;using System.Collections;using System.Text;using System.Runtime.InteropServices; using ...

  3. python基础学习十 logging模块详细使用【转载】

    很多程序都有记录日志的需求,并且日志中包含的信息既有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,主要用于输出 ...

  4. python 面向对象专题(四):封装、多态、鸭子类型、类的约束、super

    https://www.cnblogs.com/liubing8/p/11321099.html 目录 Python面向对象04 /封装.多态.鸭子类型.类的约束.super 1. 封装 2. 多态 ...

  5. python自定义封装logging模块

    #coding:utf-8 import logging class TestLog(object): ''' 封装后的logging ''' def __init__(self , logger = ...

  6. python实现单例模式的三种方式及相关知识解释

    python实现单例模式的三种方式及相关知识解释 模块模式 装饰器模式 父类重写new继承 单例模式作为最常用的设计模式,在面试中很可能遇到要求手写.从最近的学习python的经验而言,singlet ...

  7. python 自动化之路 logging日志模块

    logging 日志模块 http://python.usyiyi.cn/python_278/library/logging.html 中文官方http://blog.csdn.net/zyz511 ...

  8. 【python接口自动化】- logging日志模块

    前言:我们之前运行代码时都是将日志直接输出到控制台,而实际项目中常常需要把日志存储到文件,便于查阅,如运行时间.描述信息以及错误或者异常发生时候的特定上下文信息. logging模块介绍 ​ Pyth ...

  9. Python模块学习:logging 日志记录

    原文出处: DarkBull    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...

随机推荐

  1. 生成代码的代码 之 POJO生成器 之二 模板实现

    在之前的一篇博客中,我们写了利用node.js来生成JAVA的POJO代码的方法.有评论说可以利用模板来做这件事.当时认为模板只能做简单的字符串替换,所以可能无法完成任务.但是,仔细的学习了一个模板 ...

  2. python中大于0的元素全部转化为1,小于0的元素全部转化为0的代码

    [code] """ 大于0的元素全部转化为1 """ np_arr = np.array([[1 ,2, 3, 4]]) print(&q ...

  3. JMP地址公式推导

    以上有个问题:为什么同样的汇编指令JMP 12345678却对应不同的机器码呢? 首先,机器码E9表明这是一个近跳转(Near Jmp) 这里需要补充下相关知识: JMP分3种: ①短跳转(Short ...

  4. rtp header

    rtp协议基于udp传输,流媒体音视频数据被封装在rtp中,通过rtp协议进行实时的传输. 一.rtp协议头格式 The RTP header has a minimum size of 12 byt ...

  5. Django model转字典的几种方法

    平常的开发过程中不免遇到需要把model转成字典的需求,尤其是现在流行前后端分离架构,Json格式几乎成了前后端之间数据交换的标准,这种model转dict的需求就更多了,本文介绍几种日常使用的方法以 ...

  6. ActiveMQ——activemq的报错见解javax.jms.JMSException: Software caused connection abort: recv failed

    activeMQ出现javax.jms.JMSException: Software caused connection abort: recv failed的问题解决 一直找不到原因,原来是在本地的 ...

  7. eclipse安装quick text search插件,全文搜索

    主要有两种方法 1.InstaSearch 同样可以做到workspace下的全文搜索 可以使用eclipse marktplace中搜索instaSearch,与普通软件安装类似 安装成功后的界面如 ...

  8. 使用Akka构建集群(一)

    概述 Akka提供的非常吸引人的特性之一就是轻松构建自定义集群,这也是我要选择Akka的最基本原因之一.如果你不想敲太多代码,也可以通过简单的配置构建一个非常简单的集群.本文为说明Akka集群构建的学 ...

  9. Trace & Error log in file

    1. Log机制 做一些大型项目的时候,对代码的调试最有效的办法往往是最直接.最简单的log机制: 即对可以出设置打印店,对应打印信息进行调试(当然是有gdb也许你会觉得很高大上,但是实际项目中,gd ...

  10. (微信小程序)一 : 初识微信小程序

    首先看过angularjs的同学们在看微信小程序的创始文件应该不算很陌生吧. 需要看的 先是文件目录 看完这个目录..得知 ( 一 )    pages   他存放于多个页面 如 index ,log ...