玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python logging模块记录程序运行日志代码

python 培训

python的方法来记录日志,需要利用python logging模块,来记录程序运行中的日志。

Python logging模块记录程序运行日志代码编写之前,要先知道它的思路:
思路及使用方法:
(1)在需要使用该模块的地方import logger
(2)然后就能使用了
例如: logger.log_debug("this is a test")
        logger.log_info(["ok","error","fail"])

在编写这段代码的过程中,遇到了一些问题。希望能有大牛帮我一起解决一下。
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]
这段代码是获取调用该python 函数的模块的名字的,用于创建日志文件名

我想问的问题是:比如:模块A.py用到模块B.py,在B中也是得到模块A的名字.
1.有没有方法得到B的模块名.
2.有没有方法得到调用时的行号

#!/usr/bin/env python
#-*-coding:utf-8-*-
#Filename:

import os
import sys
import errno
import logging
import logging.handlers
import traceback

__author__ = "maqiang.jacky <mq.jacky@gmail.com>"
__version__ = 1.0
__date__ = "11-4-2"

try:
    from config.config import conf
except ImportError:
    conf = {}
    conf["logger"] = {}
    conf["logger"]["path"] = "%s%slogs" % (os.path.dirname(os.path.realpath(__file__)), os.sep)
    conf["logger"]["format"] = "%(asctime)s>>(PID:%(process)d,FUNCNAME:%(funcName)s,LINENO:%(lineno)d)-%(levelname)s-%(message)s"
    conf["logger"]["backupcount"] = 7
    conf["logger"]["level"]=logging.DEBUG
except :
    raise 

class logger():
    """
    """
    Ins = None

    @staticmethod
    def getLogger(modname):
        """
        """
        if None == logger.Ins:
            logger.Ins = InitLogging(modname)
        return logger.Ins

def InitLogging(modname):
    """
    """
    logger = logging.getLogger(modname)
    format = logging.Formatter(conf["logger"]["format"])

    logpath = conf["logger"]["path"]
    try:
        os.makedirs(logpath)
    except OSError,e:
        if e.errno != errno.EEXIST:
            print "logger make dir error:",e
            raise 

    logfile = os.path.join(logpath, "%s.log" % modname)
    handler = logging.handlers.TimedRotatingFileHandler(filename = logfile
                                                        , when = "D"
                                                        , backupCount = conf["logger"]["backupcount"])
    handler.setFormatter(format)
    logger.addHandler(handler)
    logger.setLevel(conf["logger"]["level"])
    return logger

def log(level, msg, *args, **kwargs):
    """
www.iplaypython.com
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).log(level, msg, args, kwargs)

def log_info(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).info(msg)

def log_debug(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).debug(msg)

def log_warning(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).warning(msg)

def log_error(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).error(msg)

def log_exception(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).exception(msg)

def log_critical(*msg):
    """
    """
    exst = traceback.extract_stack()
    filepath = exst[-2][0]
    file = os.path.split(filepath)[-1]
    moduleName = os.path.splitext(file)[0]

    logger.getLogger(moduleName).critical(msg)

def main(argv):
    """
    """
    print "i am run."

if __name__ == "__main__":
    """
    """
    main(sys.argv[1:])
    sys.exit()

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/other/o2483.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-03-30 11:42 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部