【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 ...
随机推荐
- Three.js黑暗中的萤火虫
效果图 demo import './index.css'; // stats var stats; (function(){ stats = new Stats(); document.body.a ...
- Ubuntu下编写C语言程序
新建C文件,新建一个文件用touch,新建文件夹用mkdir. 打开文本编辑器,编辑C文件,命令用gedit xxx.C 编写C程序,Ctrl+S保存 编译运行 1.gcc命令是编译 -o是可选项 是 ...
- ACCESS中如何比较日期和时间,使用DateDiff函数
DateDiff,语法如下:DateDiff( 间隔字符, 日期1, 日期2 [,firstdayofweek[, firstweekofyear]])一般使用 DateDiff( 间隔字符, 日期1 ...
- minerd.exe 处理
:top TASKKILL /F /IM "minerd.exe" Goto top and then searching the file system for minerd.e ...
- smack 监听不同packet机制
之前做即时通讯,扒了smack源码来参考.说下其中解包后进行通知的机制. Filter类:accept(Packet packet)函数,传入packet在此函数中进行对比判断,返回true 则通过此 ...
- Git的配置和使用帮助
Git的配置和使用帮助 1.Git的配置 ============== Git有三个地方可以存放配置:系统级配置文件/etc/gitconfig.用户级配置文件~/.gitconfig和仓库级配置文件 ...
- 【bzoj1455】罗马游戏
1455: 罗马游戏 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1061 Solved: 439[Submit][Status][Discuss] ...
- BootstrapValidator:表单验证神器
前言:做Web开发的我们,表单验证是再常见不过的需求了.友好的错误提示能增加用户体验.博主搜索bootstrap表单验证,搜到的结果大部分都是文中的主题:bootstrapvalidator.今天就来 ...
- 新装的Ubuntu没有ipconfig和ping命令
新装的Ubuntu或者Docker pull的Ubuntu镜像创建的容器没有ipconfig和ping命令 解决办法: 1.apt-get update 2.安装和ifconfig有关的工具 apt ...
- ROS 下使用3D激光雷达 velodyne vlp-16
Velodyne VLP16型激光雷达横向视角360°,纵向视角30° 系统和ROS版本:Ubuntu 14.04 ,ros indigo 1. 安装驱动 sudo apt-get install r ...