首页 文章

几个基本的python日志问题

提问于
浏览
0

我正在通过Logging HOWTOlogging docstomordonez/logging tutorial来处理日志记录系统 . 当我向类添加日志记录时,日志信息不会显示 MyClass.__init__() 但它确实显示 MyClass.obj_name() . 这是为什么?

如何在日志记录输出中包含带有 funcName info的类名?我读过的文档和其他SO问题看起来像我可能需要编写自定义格式化程序?或类似的东西?是否有任何非docs.python.org网站都有详细的演练,介于基础和高级之间?谢谢!

import logging

logger = logging.getLogger('application')
logger.setLevel(logging.DEBUG)
# # create file handler which logs debug messages
# fh = logging.FileHandler('output.log.txt')
# fh.setLevel(logging.DEBUG)
# # create console handler which logs debug messages
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s %(funcName)s - %(levelname)s - %(message)s')
# fh.setFormatter(formatter)
ch.setFormatter(formatter)
# # add handlers to logger
# logger.addHandler(fh)
logger.addHandler(ch)


class MyClass():
    def init():
        logger.info('creating an instance of MyClass object')

    def obj_name(self):
        logger.info('declare name')


def main():
    myobj = MyClass()
    # print(dir(myobj))
    myobj.obj_name()

if __name__ == "__main__":
    main()

完成输出:

PS D:\0_program_dev>'C:\Python\Python37\python.exe' 'd:\0_program_dev\hands_of_ada_book_generator\logging_tools.py'
    application obj_name - INFO - declare name
PS D:\0_program_dev>

1 回答

  • 0

    不确定这是否有帮助:

    import logging
    from functools import wraps
    import sys
    stdouthandler = logging.StreamHandler(sys.stdout)
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s %(levelname)s: %(message)s",
                        handlers=[stdouthandler])
    
    
    def status(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            logging.debug(f"hello {func.__name__}")
            result = func(*args, **kwargs)
            return result
        return wrapper
    
    class MyClass():
        @status
        def __init__(self):
            logging.debug(f"created instance of {self.__class__}")
    
        @status
        def my_function(self):
            logging.debug(f"here is a function {sys._getframe().f_code.co_name} of {self.__class__.__name__}")
    
    
    my_obj = MyClass()
    my_obj.my_function()
    

    2018-12-08 22:43:40,503 DEBUG:hello init 2018-12-08 22:43:40,503 DEBUG:创建类'main.MyClass'的实例2018-12-08 22:43:40,503 DEBUG:你好my_function 2018-12-08 22:43:40,503 DEBUG:这是myClass的函数my_function

相关问题