推荐学习书目
› 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
azev
V2EX  ›  Python

Python 的 logging 不是实时的?

  •  
  •   azev · Jun 1, 2021 · 4370 views
    This topic created in 1984 days ago, the information mentioned may be changed or developed.

    头次用这个 发现日志文件里记录的时间点都那么接近 都是差不多程序运行结束时的时刻
    这是怎么回事?之前用 js,java 啥的不是这样啊

    18 replies  •  2021-06-08 16:12:09 +08:00
    nowheremanx
    nowheremanx
    Jun 1, 2021
    1
    flush 一下?
    simple2025
    simple2025
    Jun 1, 2021
    2
    不应该呀
    ClericPy
    ClericPy
    Jun 1, 2021
    3
    无代码猜不到
    jdhao
    jdhao
    Jun 1, 2021 via Android❤️1
    4
    上代码啊,没代码你说个蛋蛋
    leavic
    leavic
    Jun 1, 2021❤️1
    5
    确实不是实时的,尤其是有 Exception 的时候,logging 还没完成程序就结束了都可能。
    lzjamao
    lzjamao
    Jun 1, 2021❤️1
    6
    这要看 logging 的内部实现了。
    IO 分为有缓冲和无缓冲的。
    有缓冲,不是立即写到磁盘的。
    stderr 是不做缓存立即写的,你可以换个 error 输出接口试试
    或者找下是否有接口,设置缓冲区模式 setvbuf
    luckylo
    luckylo
    Jun 2, 2021 via Android
    7
    确实是。我也碰到过。还把别人怼了。结果自己搞错了。尴尬。
    myCupOfTea
    myCupOfTea
    Jun 2, 2021
    8
    正常啊,就算是 print 他都是有缓冲的啊
    azev
    azev
    OP
    Jun 2, 2021
    9
    @nowheremanx 每句都要跟一个 flush 吗?
    azev
    azev
    OP
    Jun 2, 2021
    10
    @myCupOfTea 貌似其他语言没有这个问题
    azev
    azev
    OP
    Jun 2, 2021
    11
    @lzjamao 开始我是输出到控制台的 发现记录的时间点不对 后来输出到文件 还是一样
    azev
    azev
    OP
    Jun 2, 2021
    12
    @luckylo 确实 这个问题太奇葩了
    ruanimal
    ruanimal
    Jun 2, 2021
    13
    @azev 你代码有问题,logging 到控制台应该是无缓冲的
    myCupOfTea
    myCupOfTea
    Jun 2, 2021
    14
    发现日志文件里记录的时间点都那么接近
    你这个应该是自己的问题了
    no1xsyzy
    no1xsyzy
    Jun 2, 2021
    15
    可是 logging.StreamHandler.emit 在 19 年前刚引入 logging 包就有 flush
    https://github.com/python/cpython/blame/bb3e0c240bc60fe08d332ff5955d54197f79751c/Lib/logging/__init__.py#L1102
    不过 python>=3,<3.7 的话始终有单行 buffer 。

    而且记录时间不是在打印后,而是在打印前,怎么可能因为有 buffer 导致记录的时间点改变?
    flyingghost
    flyingghost
    Jun 2, 2021
    16
    啊不,有 buffer 正常,buffer 还会影响时间戳就不正常了。
    你确定你的姿势没问题吗?
    luckyc
    luckyc
    Jun 3, 2021
    17
    loguru 解君愁
    lusi1990
    lusi1990
    Jun 8, 2021
    18
    pycharm 里面有个环境变量 PYTHONUNBUFFERED=1
    不知道你有没有?
    ![Is PYTHONUNBUFFERED=TRUE a good idea]( https://github.com/aws/amazon-sagemaker-examples/issues/319)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1881 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 07:19 · PVG 15:19 · LAX 23:19 · JFK 02:19
    ♥ Do have faith in what you're doing.