#coding: utf-8
import logging
import logging.config
 
class SingleLevelFilter(object):
    def __init__(self, pass_level):
        self.pass_level = pass_level
 
    def filter(self, record):
        if self.pass_level == record.levelno:
            return True
        return False
 
LEVEL_COLOR = {
    logging.DEBUG: '\33[2;39m',
    logging.INFO: '\33[0;37m',
    logging.WARN: '\33[4;35m',
    logging.ERROR: '\33[5;31m',
    logging.FATAL: '\33[7;31m'
}
 
 
class ScreenHandler(logging.StreamHandler):
    def emit(self, record):
        try:
            msg = self.format(record)
            stream = self.stream
            fs = LEVEL_COLOR[record.levelno] + "%s\n" + '\33[0m'
            try:
                if isinstance(msg, unicode) and getattr(stream, 'encoding', None):
                    ufs = fs.decode(stream.encoding)
                    try:
                        stream.write(ufs % msg)
                    except UnicodeEncodeError:
                        stream.write((ufs % msg).encode(stream.encoding))
                else:
                    stream.write(fs % msg)
            except UnicodeError:
                stream.write(fs % msg.encode("UTF-8"))
 
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
 
def init_logger():
    conf = {'version': 1,
            'disable_existing_loggers': True,
            'incremental': False,
            'formatters': {'myformat1': {'class': 'logging.Formatter',
                                         'format': '|%(asctime)s|%(name)s|%(filename)s|%(lineno)d|%(levelname)s|%(message)s',
                                         'datefmt': '%Y-%m-%d %H:%M:%S'}
                          },
            'filters': {'filter_by_name': {'class': 'logging.Filter',
                                           'name': 'logger_for_filter_name'},
 
                        'filter_single_level_pass':{'()': 'mylogger.SingleLevelFilter',
                                                    'pass_level': logging.WARN}
                        },
            'handlers': {'console': {'class': 'logging.StreamHandler',
                                      'level': 'INFO',
                                      'formatter': 'myformat1',
                                      'filters': ['filter_single_level_pass', ]},
 
                         'screen': {'()': 'mylogger.ScreenHandler',
                                    'level': logging.INFO,
                                    'formatter': 'myformat1',
                                    'filters': ['filter_by_name', ]}
                        },
            'loggers': {'logger_for_filter_name': {'handlers': ['console', 'screen'],
                                                   'filters': ['filter_by_name', ],
                                                   'level': 'INFO'},
                        'logger_for_all': {'handlers': ['console', ],
                                           'filters': ['filter_single_level_pass',],
                                           'level': 'INFO',
                                           'propagate': False}
                       }
            }
    logging.config.dictConfig(conf)
 
if __name__ == '__main__':
    init_logger()
    logger_for_filter_name = logging.getLogger('logger_for_filter_name')
    logger_for_filter_name.debug('logger_for_filter_name')
    logger_for_filter_name.info('logger_for_filter_name')
    logger_for_filter_name.warn('logger_for_filter_name')
    logger_for_filter_name.error('logger_for_filter_name')
    logger_for_filter_name.critical('logger_for_filter_name')
 
    logger_for_all = logging.getLogger('logger_for_all')
    logger_for_all.debug('logger_for_all')
    logger_for_all.info('logger_for_all')
    logger_for_all.warn('logger_for_all')
    logger_for_all.error('logger_for_all')
    logger_for_all.critical('logger_for_all')</span>

logging dictconfig的更多相关文章

  1. Python标准模块--logging

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  2. 以打印日志为荣之logging模块详细使用

    啄木鸟社区里的Pythonic八荣八耻有一条: 以打印日志为荣 , 以单步跟踪为耻; 很多程序都有记录日志的需求,并且日志中包含的信息既有正常的程序访问日志,还可能有错误.警告等信息输出,python ...

  3. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  4. Python常用模块--logging

    (转载) 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python内置的标准模块,主要用于 ...

  5. Python入门之logging模块

    本章目录: 一.logging模块简介 二.logging模块的使用 三.通过JSON或者YMAL文件配置logging模块 ===================================== ...

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

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

  7. Python标准模块--logging(转载)

    转载地址:http://www.cnblogs.com/zhbzz2007/p/5943685.html#undefined Python标准模块--logging 1 logging模块简介 log ...

  8. python logging模块【转载】

    转自:https://www.cnblogs.com/dahu-daqing/p/7040764.html 参考:老顽童log模块,讲的很细致,基本上拿到手就可以直接用了,很赞 1 logging模块 ...

  9. [转载] 每个 Python 程序员都要知道的日志实践

    原文: http://python.jobbole.com/81666/ 在现实生活中,记录日志非常重要.银行转账时会有转账记录:飞机飞行过程中,会有黑盒子(飞行数据记录器)记录飞行过程中的一切.如果 ...

随机推荐

  1. python程序—系统检测

    监控系统内存,CPU,硬盘的使用情况,到达阈值时会自动发送邮件报警! import yagmail import psutil def sendmail(subject,contents): #连接邮 ...

  2. 基于SVD的图像压缩

    算法简介 算法实现 我只是简单处理了一下图像的灰度值,如果要处理RGB值的话,就需要分别进行SVD分解,最后再合起来即可. import numpy as np from PIL import Ima ...

  3. js循环中使用async/await踩过的坑

    最近写koa的时候遇见需要在循环中使用async/await的情况,当然第一反应就是直接上forEach,然后就直接翻车了... 直接上代码: function handleSql(val) { re ...

  4. vlog.hpp

    //vov #ifndef VLOG_HPP #define VLOG_HPP #include <sys/time.h> #include <unistd.h> #ifnde ...

  5. requests库详解 --Python3

    本文介绍了requests库的基本使用,希望对大家有所帮助. requests库官方文档:https://2.python-requests.org/en/master/ 一.请求: 1.GET请求 ...

  6. Flutter采坑之路 用真机跑起来的时候提示 initGradle失败,IO异常,downloading Gradle-4.6-all.zip失败

    这个异常就是Gradle下载异常,进而下面会提示一行IO异常 我这里的原因就是Gradle对应的4.6-all版本下载不下来(一般情况下确实很难下载下来) 所以在正常AS工程呢,我们选择一下Gradl ...

  7. LDA(线性判别分类器)学习笔记

    Linear Discriminant Analysis(线性判别分类器)是对费舍尔的线性鉴别方法(FLD)的归纳,属于监督学习的方法. LDA的基本思想是将高维的模式样本投影到最佳鉴别矢量空间,以达 ...

  8. php 两次encodeURI,解决浏览器跳转请求页乱码报错找不到页面的bug

    Not Found The requested URL /index.php/XXX/mid/97329240798095910/bname/3000T/D/sname/水泥粉磨/un ...

  9. 『高性能模型』Roofline Model与深度学习模型的性能分析

    转载自知乎:Roofline Model与深度学习模型的性能分析 在真实世界中,任何模型(例如 VGG / MobileNet 等)都必须依赖于具体的计算平台(例如CPU / GPU / ASIC 等 ...

  10. JDK8下Object类源码理解

    JDK8中Object类提供的方法: package java.lang; /** * Class {@code Object} is the root of the class hierarchy. ...