【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 ...
随机推荐
- 结合spring 实现自定义注解
注解类 import java.lang.annotation.*; /** * Created by Administrator on 2016/6/28. */ //ElementType.MET ...
- Java调用Webservice(asmx)的几个例子
Java调用Webservice(asmx)的几个例子 2009-06-28 17:07 写了几个调用例子: 1. import org.apache.axis.client.*;import org ...
- Location - BOM对象
Location 对象 Location 对象包含有关当前 URL 的信息. Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问. 例子 把用户 ...
- 第01章 开发准备(对最新版的RN进行了升级)1-3+项目结构介绍
- Composer安装(windows)
https://files.cnblogs.com/files/wlphp/Composer-Setup.zip 先下载这个安装包,一直下一步 然后设置composer全局中国景象 composer ...
- mongo 修改器 $inc/$set/$unset/$pop/$push/$pull/$addToSet
mongo $inc 可以对集合里面的某些值是数字的增减.看代码 $set 可以进行修改,并且不存在的时候默认添加. 同时还能该变数据的类型. 还可以该变内嵌元素的值 用.调用 $unset 删除 ...
- 13-STL-二分查找
STL中提供-二分查找算法(binary_search lower_bound upper_bound equal_range STL包含四种不同的二分查找算法,binary_search ...
- ROS naviagtion analysis: costmap_2d--Layer
博客转载自:https://blog.csdn.net/u013158492/article/details/50493113 这个类中有一个LayeredCostmap* layered_costm ...
- pandas dataframe 满足条件的样本提取
pandas 的dataframe 对 数据查询可以通过3种方式 . 预备知识: 1. pandas 的索引和label都是从0开始的计数的 2. 时间切片都是左闭右开的. [5:6,:] 只会输出 ...
- Part10-C语言环境初始化-C与汇编混合编程lesson4
1.为什么要混合编程 汇编语言:执行效率高:编写繁琐: 执行效率高:能够更直接地控制处理器. c语言:可读性强,移植性好,调试方便. 1.汇编调用c函数 2.c调用汇编函数 汇编语言定义的函数(标号) ...