Skip to content

Instantly share code, notes, and snippets.

@shiweifu
Created July 13, 2012 05:41
Show Gist options
  • Save shiweifu/3102955 to your computer and use it in GitHub Desktop.
Save shiweifu/3102955 to your computer and use it in GitHub Desktop.
日志封装
#!/usr/bin/env python
#coding: utf-8
#author: shiweifu
#mail : [email protected]
import logging
class LogFunc:
pass
logfunc = LogFunc()
#------------------------------log------------------------------#
def get_format_log(**dic):
"""遍历dic,合并kv成为最终字符串
>>> print get_format_log(a="abc")
a:abc
"""
_log = ""
for key in dic.keys():
tmp = "".join((key, ":", dic[key]))
_log = " ".join((_log, tmp))
return _log.strip()
def log(logger, log_type):
wrapper = lambda **kw: logger.log(log_type, get_format_log(**kw))
return wrapper
def initlog(fileName="logfile"):
""" 初始化logger对象使用函数内的 fmt 作为格式
>>> import logging
>>> ret = initlog("abc")
>>> print isinstance(ret, logging.RootLogger)
True
"""
global logfunc
logger = logging.getLogger()
hdlr = logging.FileHandler(fileName)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.NOTSET)
logfunc.debug_log = log(logger, logging.DEBUG)
logfunc.warn_log = log(logger, logging.WARN)
logfunc.error_log = log(logger, logging.ERROR)
return logger
@shiweifu
Copy link
Author

以前是写在其他文件中的,现在摘出来了,更加通用了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment