python整理十三——迷你日志
2008-09-13 15:55
176 查看
写个小点的程序,写日志太麻烦了,大点的程序,不写日志是万万不行的,鉴于日志频繁的使用,对python的logging稍微封装一下,适合自己的需求:
#coding=utf-8
import os, logging, sys
from logging.handlers import RotatingFileHandler as RFHandler
class CommLogger:
LOG_FILE_SIZE_MAX = 1024 # byte
LOG_FILE_BACKUP_MAX = 5 #
def __init__(self):
self.__log_argv = {'dirname' : os.path.join(os.path.dirname(__file__), 'log' ),
'name_default' : 'log_default',
'extend' : '.log',
}
self.__log_fmt_t = '%(f_info)s%(ctrl)s%(ctime)s%(ctrl)s%(msg)s%(ctrl)s%(tail)s%(ctrl)s' % /
{'f_info' : 'File:%(pathname)s,line %(lineno)d,function: %(funcName)s',
'ctime' : '%(asctime)s [%(levelname)s]',
'msg' : '%(message)s',
'tail' : '-' * 80 ,
'ctrl' : os.linesep,}
self.__log_fmt = logging.Formatter(self.__log_fmt_t)
self.__loggers = {}
def __getLogPath(self, log_name):
fpath = os.path.join(self.__log_argv['dirname'], log_name)
if not os.path.exists(fpath):
os.makedirs(fpath)
return fpath
def __initLog(self, log_name, level, bPrint):
if log_name not in self.__loggers:
logger = logging.getLogger(log_name)
if len(logger.handlers) == 0:
if bPrint:
chdlr = logging.StreamHandler(sys.stdout)
chdlr.setFormatter(self.__log_fmt)
logger.addHandler(chdlr)
else:
fname = os.path.join(self.__getLogPath(log_name), log_name + self.__log_argv['extend'])
fhdlr = RFHandler(fname, 'a', CommLogger.LOG_FILE_SIZE_MAX, CommLogger.LOG_FILE_BACKUP_MAX,)
fhdlr.setFormatter(self.__log_fmt)
logger.addHandler(fhdlr)
logger.setLevel(level)
self.__loggers[log_name] = logger
return self.__loggers[log_name]
def getLogger(self, log_name = None, bPrint = False, level= logging.DEBUG, ):
if log_name is None:
log_name = self.__log_argv['name_default']
if log_name not in self.__loggers:
self.__initLog(log_name, level, bPrint)
return self.__loggers[log_name]
def mini_log(fn):
def moniter(*args, **argkv):
return fn(*args, **argkv)
logger = CommLogger().getLogger(fn.func_name)
log_info = {'fn_name' : repr(fn.func_name), 'fn_code' : fn.func_code, 'ctrl' : os.linesep}
logger.info('The function of %(fn_name)s has been running.%(ctrl)s%(fn_code)s' % log_info)
return moniter
@mini_log
def test():
print 'test logging module.'
if __name__ == '__main__':
cCls = CommLogger()
log0 = cCls.getLogger()
log1 = cCls.getLogger('log1', True)
for i in range(3):
log0.debug('debug')
log0.info('info')
log0.warning('warn')
log0.error('error')
log0.critical('critical')
log1.debug('debug')
log1.info('info')
log1.warn('warn')
log1.error('error')
log1.critical('critical')
test()
print 'end___'
#coding=utf-8
import os, logging, sys
from logging.handlers import RotatingFileHandler as RFHandler
class CommLogger:
LOG_FILE_SIZE_MAX = 1024 # byte
LOG_FILE_BACKUP_MAX = 5 #
def __init__(self):
self.__log_argv = {'dirname' : os.path.join(os.path.dirname(__file__), 'log' ),
'name_default' : 'log_default',
'extend' : '.log',
}
self.__log_fmt_t = '%(f_info)s%(ctrl)s%(ctime)s%(ctrl)s%(msg)s%(ctrl)s%(tail)s%(ctrl)s' % /
{'f_info' : 'File:%(pathname)s,line %(lineno)d,function: %(funcName)s',
'ctime' : '%(asctime)s [%(levelname)s]',
'msg' : '%(message)s',
'tail' : '-' * 80 ,
'ctrl' : os.linesep,}
self.__log_fmt = logging.Formatter(self.__log_fmt_t)
self.__loggers = {}
def __getLogPath(self, log_name):
fpath = os.path.join(self.__log_argv['dirname'], log_name)
if not os.path.exists(fpath):
os.makedirs(fpath)
return fpath
def __initLog(self, log_name, level, bPrint):
if log_name not in self.__loggers:
logger = logging.getLogger(log_name)
if len(logger.handlers) == 0:
if bPrint:
chdlr = logging.StreamHandler(sys.stdout)
chdlr.setFormatter(self.__log_fmt)
logger.addHandler(chdlr)
else:
fname = os.path.join(self.__getLogPath(log_name), log_name + self.__log_argv['extend'])
fhdlr = RFHandler(fname, 'a', CommLogger.LOG_FILE_SIZE_MAX, CommLogger.LOG_FILE_BACKUP_MAX,)
fhdlr.setFormatter(self.__log_fmt)
logger.addHandler(fhdlr)
logger.setLevel(level)
self.__loggers[log_name] = logger
return self.__loggers[log_name]
def getLogger(self, log_name = None, bPrint = False, level= logging.DEBUG, ):
if log_name is None:
log_name = self.__log_argv['name_default']
if log_name not in self.__loggers:
self.__initLog(log_name, level, bPrint)
return self.__loggers[log_name]
def mini_log(fn):
def moniter(*args, **argkv):
return fn(*args, **argkv)
logger = CommLogger().getLogger(fn.func_name)
log_info = {'fn_name' : repr(fn.func_name), 'fn_code' : fn.func_code, 'ctrl' : os.linesep}
logger.info('The function of %(fn_name)s has been running.%(ctrl)s%(fn_code)s' % log_info)
return moniter
@mini_log
def test():
print 'test logging module.'
if __name__ == '__main__':
cCls = CommLogger()
log0 = cCls.getLogger()
log1 = cCls.getLogger('log1', True)
for i in range(3):
log0.debug('debug')
log0.info('info')
log0.warning('warn')
log0.error('error')
log0.critical('critical')
log1.debug('debug')
log1.info('info')
log1.warn('warn')
log1.error('error')
log1.critical('critical')
test()
print 'end___'
相关文章推荐
- Python学习笔记整理(十三)Python模块
- python-整理-logging日志
- Nginx服务整理 日志分析(shell+python)
- Python模块整理(三):子进程模块subprocess
- python网络爬虫实战--重点整理
- 《剑指offer》python答案整理(1)
- 基于python实现日志收集
- 整理汇总Python框架、库以及软件资源
- python日志记录模块实例及改进
- 运维中的日志切割操作梳理(Logrotate/python/shell脚本实现)
- linux下python学习笔记(十三)之备份实例1
- python日志输出
- Python学习笔记整理(七)Python中的元组和文件及其他
- python 小整数池 和intern 【整理】
- python串口编程整理
- Python——问题解决方法整理
- 【Python】内置函数方法详解整理
- 【python】日志模块
- Python学习笔记整理(十一)python的while和for循环
- Python学习日志20150717-Python核心编程基础教程之Python运算符、运算符优先级、表达式简介