【python】Python的logging模块封装
#!/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模块封装的更多相关文章
- Python自建logging模块
本章将介绍Python内建模块:日志模块,更多内容请从参考:Python学习指南 简单使用 最开始,我们用最短的代码体验一下logging的基本功能. import logging logger = ...
- Python日志输出——logging模块
Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...
- Python实战之logging模块使用详解
用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...
- Python中的logging模块就这么用
Python中的logging模块就这么用 1.日志日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICALDEBUG:详细的信息,通常只出现在诊断问题 ...
- python中日志logging模块的性能及多进程详解
python中日志logging模块的性能及多进程详解 使用Python来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析.Python的 ...
- logging模块封装
logging模块封装 #!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import logging import env ...
- Python 中 对logging 模块进行封装,记录bug日志、日志等级
是程序产生的日志 程序员自定义设置的 收集器和渠道级别那个高就以那个级别输出 日志和报告的作用: 报告的重点在于执行结果(执行成功失败,多少用例覆盖),返回结果 日志的重点在执行过程当中,异常点,哪里 ...
- Python自动化之logging模块
Logging模块构成 主要分为四个部分: Loggers:提供应用程序直接使用的接口 Handlers:将Loggers产生的日志传到指定位置 Filters:对输出日志进行过滤 Formatter ...
- Python中的logging模块
http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...
- python日志记录-logging模块
1.logging模块日志级别 使用logging模块简单示例: >>>import logging >>>logging.debug("this's a ...
随机推荐
- java成神之——接口,泛型,类
接口 接口定义 默认方法 函数式接口 泛型 泛型类 泛型类继承 类型限定 泛型方法 泛型接口 类 构造函数 类的继承 抽象类 instanceof运算符 内部类 equals 结语 接口 接口定义 j ...
- springboot成神之——spring boot,spring jdbc和spring transaction的使用
本文介绍spring boot,spring jdbc和spring transaction的使用 项目结构 依赖 application model层 mapper层 dao层 exception层 ...
- ssh secure shell 乱码问题
1. 执行命令 locale 查看,出现如下: [root@catxjd ~]# locale LANG=zh_CN.GB2312 LC_CTYPE="zh_CN.GB2312" ...
- JavaScript第二节
1.动态属性 引用类型可以动态的添加属性,而基本类型不行. 2.复制变量值 3.检测类型 执行环境和作用域 没有块级作用域 引用类型 1.Object类型 2.Array类型 数组初始化: 检测数组: ...
- MySQL OSC(在线更改表结构)原理
1 OSC介绍 在我们的数据库操作中,更改表结构是一个常见的操作,而当我们的表数据量非常大时,我们更改表结构的时间是非 常的长,并且在跟改期间,会生成一个互斥锁,阻塞对整个表的所有操作,这样,对于我们 ...
- 切面(Aspect)获取请求参数和返回值
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求, ...
- mahout in Action2.2-给用户推荐图书(2)-分析对用户推荐书目的结果
2.2.3 Analyzing the output 在之前的程序运行结果中我们得到的结果输出是: RecommendedItem [item:104, value:4.257081] 程序要求选择一 ...
- 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 5 Octave Tutorial—5.5 控制语句: for, while, if 语句
5.5 控制语句: for, while, if 语句 参考视频: 5 - 5 - Control Statements_ for, while, if statements (13 min).mkv ...
- elasticsearch2.x插件之一:kopf
kopf kopf is a simple web administration tool for elasticsearch written in JavaScript + AngularJS + ...
- 【HDU5391】Zball in Tina Town
[题目大意] 一个球初始体积为1,一天天变大,第一天变大1倍,第二天变大2倍,第n天变大n倍.问当第 n-1天的时候,体积变为多少.注意答案对n取模. [题解] 根据威尔逊定理:(n-1)! mod ...