V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
frmongo
V2EX  ›  Python

怎样优雅的创建 log?

  •  
  •   frmongo · 2020-12-08 21:24:59 +08:00 · 2010 次点击
    这是一个创建于 1232 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如我有如下的 python 程序,为了方便调试,每个函数都加了很多打印,有没有办法把这些打印都自动保存到一个 log.txt 里 最好能将进入函数、函数中执行步骤、退出函数的 print 的输出都记录下来保存进 log.txt 里

    def aa():
        print("enter aa")
        # do sth
        print("quit aa")
    
    def bb():
        print("enter bb")
        # do sth
        print("quit bb")
    
    def cc():
        print("enter cc")
        # do sth
        print("quit cc")
    
    def main()
        print("begin")
        aa()
        bb()
        cc()
        print("all end")
    
    main()
    
    7 条回复    2020-12-09 16:53:43 +08:00
    nightwitch
        1
    nightwitch  
       2020-12-08 21:27:10 +08:00
    frmongo
        2
    frmongo  
    OP
       2020-12-08 21:31:55 +08:00
    @nightwitch #1 如果用 logging,函数内部也想用同一个 logging 对象,是不是用装饰器比较好..这个不太熟悉
    no1xsyzy
        3
    no1xsyzy  
       2020-12-08 21:40:39 +08:00
    @frmongo logger 对象一般分模块
    如果你是想在函数前后做的话确实是修饰器。
    一说不要用 trace 当 debug……
    你可能需要 VizTracer
    frmongo
        4
    frmongo  
    OP
       2020-12-09 11:29:19 +08:00
    @no1xsyzy #3 看起来很酷,我试试,谢谢
    TimePPT
        5
    TimePPT  
       2020-12-09 16:02:07 +08:00
    TimePPT
        6
    TimePPT  
       2020-12-09 16:03:04 +08:00
    如果是 debug,PySnooper 合适
    https://github.com/cool-RR/PySnooper
    frmongo
        7
    frmongo  
    OP
       2020-12-09 16:53:43 +08:00
    @TimePPT #6 多谢,炸出来一堆高手
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5247 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 05:46 · PVG 13:46 · LAX 22:46 · JFK 01:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.