#!/usr/local/python/bin
# coding=utf-8 '''Implements a simple log library. This module is a simple encapsulation of logging module to provide a more
convenient interface to write log. The log will both print to stdout and
write to log file. It provides a more flexible way to set the log actions,
and also very simple. See examples showed below: Example 1: Use default settings import log log.debug('hello, world')
log.info('hello, world')
log.error('hello, world')
log.critical('hello, world') Result:
Print all log messages to file, and only print log whose level is greater
than ERROR to stdout. The log file is located in '/tmp/xxx.log' if the module
name is xxx.py. The default log file handler is size-rotated, if the log
file's size is greater than 20M, then it will be rotated. Example 2: Use set_logger to change settings # Change limit size in bytes of default rotating action
log.set_logger(limit = 10240) # 10M # Use time-rotated file handler, each day has a different log file, see
# logging.handlers.TimedRotatingFileHandler for more help about 'when'
log.set_logger(when = 'D', limit = 1) # Use normal file handler (not rotated)
log.set_logger(backup_count = 0) # File log level set to INFO, and stdout log level set to DEBUG
log.set_logger(level = 'DEBUG:INFO') # Both log level set to INFO
log.set_logger(level = 'INFO') # Change default log file name and log mode
log.set_logger(filename = 'yyy.log', mode = 'w') # Change default log formatter
log.set_logger(fmt = '[%(levelname)s] %(message)s'
''' __author__ = "tuantuan.lv <dangoakachan@foxmail.com>"
__status__ = "Development" __all__ = ['set_logger', 'debug', 'info', 'warning', 'error',
'critical', 'exception'] import os
import sys
import logging
import logging.handlers # Color escape string
COLOR_RED='\033[1;31m'
COLOR_GREEN='\033[1;32m'
COLOR_YELLOW='\033[1;33m'
COLOR_BLUE='\033[1;34m'
COLOR_PURPLE='\033[1;35m'
COLOR_CYAN='\033[1;36m'
COLOR_GRAY='\033[1;37m'
COLOR_WHITE='\033[1;38m'
COLOR_RESET='\033[1;0m' # Define log color
LOG_COLORS = {
'DEBUG': '%s',
'INFO': COLOR_GREEN + '%s' + COLOR_RESET,
'WARNING': COLOR_YELLOW + '%s' + COLOR_RESET,
'ERROR': COLOR_RED + '%s' + COLOR_RESET,
'CRITICAL': COLOR_RED + '%s' + COLOR_RESET,
'EXCEPTION': COLOR_RED + '%s' + COLOR_RESET,
} # Global logger
g_logger = None class ColoredFormatter(logging.Formatter):
'''A colorful formatter.''' def __init__(self, fmt = None, datefmt = None):
logging.Formatter.__init__(self, fmt, datefmt) def format(self, record):
level_name = record.levelname
msg = logging.Formatter.format(self, record) return LOG_COLORS.get(level_name, '%s') % msg def add_handler(cls, level, fmt, colorful, **kwargs):
'''Add a configured handler to the global logger.'''
global g_logger if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG) handler = cls(**kwargs)
handler.setLevel(level) if colorful:
formatter = ColoredFormatter(fmt)
else:
formatter = logging.Formatter(fmt) handler.setFormatter(formatter)
g_logger.addHandler(handler) return handler def add_streamhandler(level, fmt):
'''Add a stream handler to the global logger.'''
return add_handler(logging.StreamHandler, level, fmt, True) def add_filehandler(level, fmt, filename , mode, backup_count, limit, when):
'''Add a file handler to the global logger.'''
kwargs = {} # If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename = os.path.basename(filename.replace('.py', '.log'))
filename = os.path.join('/tmp', filename) kwargs['filename'] = filename # Choose the filehandler based on the passed arguments
if backup_count == 0: # Use FileHandler
cls = logging.FileHandler
kwargs['mode' ] = mode
elif when is None: # Use RotatingFileHandler
cls = logging.handlers.RotatingFileHandler
kwargs['maxBytes'] = limit
kwargs['backupCount'] = backup_count
kwargs['mode' ] = mode
else: # Use TimedRotatingFileHandler
cls = logging.handlers.TimedRotatingFileHandler
kwargs['when'] = when
kwargs['interval'] = limit
kwargs['backupCount'] = backup_count return add_handler(cls, level, fmt, False, **kwargs) def init_logger():
'''Reload the global logger.'''
global g_logger if g_logger is None:
g_logger = logging.getLogger()
else:
logging.shutdown()
g_logger.handlers = [] g_logger.setLevel(logging.DEBUG) def set_logger(filename = None, mode = 'a', level='ERROR:DEBUG',
fmt = '[%(levelname)s] %(asctime)s %(message)s',
backup_count = 5, limit = 20480, when = None):
'''Configure the global logger.'''
level = level.split(':') if len(level) == 1: # Both set to the same level
s_level = f_level = level[0]
else:
s_level = level[0] # StreamHandler log level
f_level = level[1] # FileHandler log level init_logger()
add_streamhandler(s_level, fmt)
add_filehandler(f_level, fmt, filename, mode, backup_count, limit, when) # Import the common log functions for convenient
import_log_funcs() def import_log_funcs():
'''Import the common log functions from the global logger to the module.'''
global g_logger curr_mod = sys.modules[__name__]
log_funcs = ['debug', 'info', 'warning', 'error', 'critical',
'exception'] for func_name in log_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) # Set a default logger
set_logger()

原文地址:https://www.oschina.net/code/snippet_813668_14236

【python】Python的logging模块封装的更多相关文章

  1. Python自建logging模块

    本章将介绍Python内建模块:日志模块,更多内容请从参考:Python学习指南 简单使用 最开始,我们用最短的代码体验一下logging的基本功能. import logging logger = ...

  2. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  3. Python实战之logging模块使用详解

    用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...

  4. Python中的logging模块就这么用

    Python中的logging模块就这么用 1.日志日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICALDEBUG:详细的信息,通常只出现在诊断问题 ...

  5. python中日志logging模块的性能及多进程详解

    python中日志logging模块的性能及多进程详解 使用Python来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析.Python的 ...

  6. logging模块封装

    logging模块封装 #!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import logging import env ...

  7. Python 中 对logging 模块进行封装,记录bug日志、日志等级

    是程序产生的日志 程序员自定义设置的 收集器和渠道级别那个高就以那个级别输出 日志和报告的作用: 报告的重点在于执行结果(执行成功失败,多少用例覆盖),返回结果 日志的重点在执行过程当中,异常点,哪里 ...

  8. Python自动化之logging模块

    Logging模块构成 主要分为四个部分: Loggers:提供应用程序直接使用的接口 Handlers:将Loggers产生的日志传到指定位置 Filters:对输出日志进行过滤 Formatter ...

  9. Python中的logging模块

    http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...

  10. python日志记录-logging模块

    1.logging模块日志级别 使用logging模块简单示例: >>>import logging >>>logging.debug("this's a ...

随机推荐

  1. flask系列三之Jinja2模板

    1.如何渲染模板 模板在‘templates’文件夹下(htnl页面) 从flask中导入render_template函数---渲染html模板 在视图函数中,使用render_template 函 ...

  2. VirtualBox 桥接

    1.设置Virtual box,取消DHCP服务 管理->全局设定->网络->Host-Only->网络明细->DHCP服务器->启用服务器选项取消 2.宿机设置 ...

  3. java中的报错机制

    异常:Exception,程序运行过程中因为一些原因,使得程序无法运行下去 注意:在程序能够运行起来的情况,不是程序编译通不过 举例:读文件,点击一个按钮,文件不存在:访问数据库服务器,数据库服务器停 ...

  4. 字节流之文件输入流FileInputStream

  5. Enumeration & Class & Structure

    [Enumeration] 1.当一个枚举值类型已经确定后,可以使用shorter dot syntax来赋予其它值: 2.对一个枚举值switch的时候也可以使用short dot syntax: ...

  6. 解决nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

    nginx先监听了ipv4的80端口之后又监听了ipv6的80端口,于是就重复占用了.更加坑人的是你去看了端口占用它又把80端口释放了,是不是很囧. 解决方案是编辑nginx的配置文件 修改这一段:

  7. linux SIGSEGV 信号捕捉,保证发生段错误后程序不崩溃

    在Linux中编程的时候 有时候 try catch 可能满足不了我们的需求.因为碰到类似数组越界 ,非法内存访问之类的 ,这样的错误无法捕获.下面我们介绍一种使用捕获信号实现的异常 用来保证诸如段错 ...

  8. ArcGIS JS API实现的距离测量与面积量算

    转自https://www.cnblogs.com/deliciousExtra/p/5490937.html

  9. webservice CXF 相关面试题

    Web Service的优点(1) 可以让异构的程序相互访问(跨平台)(2) 松耦合(3) 基于标准协议(通用语言,允许其他程序访问) 1:WEB SERVICE名词解释.JSWDL开发包的介绍.JA ...

  10. 模板模式和Comparable类

    模板模式中,父类规定好了一些算法的流程,并且空出一些步骤(方法)留给子类填充 Java的数组类中静态方法sort()就是一个模板,它空出了一个compareTo的方法,留给子类填充,用来规定什么是大于 ...