#!/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. Mysql实用知识点总结

    本文介绍MYSQL相关知识,方便日常使用查阅 目录 准备 MYSQL常用命令 语言结构 sql语句 外键 自然语言全文搜索 准备 你可以使用 Navicat Premium 12 或者 MySQL W ...

  2. ulimit open files linux打开文件数设置验证

    #include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h ...

  3. Jenkins+maven+SVN构建java项目中遇到的问题及解决

    [ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a g ...

  4. TensorFlow模型保存和提取方法

    一.TensorFlow模型保存和提取方法 1. TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提取.tf.train.Saver对象saver的save方法将Tens ...

  5. codeforce467DIV2——D. Sleepy Game

    分析 这个题乍一看有点像之前在CF上做过的一道DP,也是两个人下棋,但是写着写着觉得不对···这个题是的最优策略只是player 1 如果有环则是draw,可以DFS的时候顺便判环(拓扑排序的方法), ...

  6. SpringBoot15 sell02 订单模块

    1 订单模块 1.1 MySQL数据表 订单模块涉及到两个数据表: 订单表:主要存储订单相关的基本信息 DROP TABLE IF EXISTS `order_master`; CREATE TABL ...

  7. oralce错误总结

    1>System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本. 给oracle客户端的bin目录添加““Authenticated Users”权 ...

  8. 2.Books

    Books示例说明了Qt中SQL类如何被Model/View框架使用,使用数据库中存储的信息,创建丰富的用户界面. 首先介绍使用SQL我们需要了解的类: 1.QSqlDatabase: QSqlDat ...

  9. MySQL中having与where

    having与where区别: where中不可以用聚合函数(条件字段是未分组中的字段),having中可以用聚合函(条件字段是分组后字段).不过这里也很好理解,SQL语句在执行是先执行select ...

  10. sql语句in超过1000时的写法

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...