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

python logging 模块无法打印日志道文件

  •  
  •   lvii · Mar 6, 2013 · 5332 views
    This topic created in 5014 days ago, the information mentioned may be changed or developed.
    $ python ~/logfile.py
    WARNING:root:This is warning message
    只在屏幕输出上面这句,指定的日志文件是空的
    将 logger=logging.getLogger('hello') 改为 logger=logging.getLogger() 才能输出到日志文件,不太明白为什么会这样子?


    #!/usr/bin/python2
    # coding=utf8

    import os
    import sys
    import logging
    import logging.handlers

    ## 日志级别大小关系为:NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
    log_file='myapp.log'

    logger=logging.getLogger('hello') ##########
    logger.setLevel(logging.NOTSET)

    formatter=logging.Formatter('%(asctime)s %(levelname)s %(message)s')

    file_handler=logging.handlers.RotatingFileHandler(log_file,maxBytes=1000,backupCount=5)
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)

    logging.debug('This is debug message')
    logging.info('This is info message')
    logging.warning('This is warning message')
    2 replies  •  1970-01-01 08:00:00 +08:00
    xuwenbao
    xuwenbao
    Mar 7, 2013❤️1
    1
    logger.setLevel(logging.NOTSET) 修改为 logger.setLevel(logging.DEBUG),NOTSET并不是最小的级别,而是代表继承“parent”。

    logging.debug('This is debug message')
    logging.info('This is info message')
    logging.warning('This is warning message')
    这三句改为
    logger.debug('This is debug message')
    logger.info('This is info message')
    logger.warning('This is warning message')
    lvii
    lvii
    OP
    Mar 8, 2013
    2
    @xuwenbao 兄,修改为 logger 对象后,可以输出日志到文件,但是只有 warning 日志
    debug 和 info 没有,修改日志级别为 DEBUG 后,debug 和 info 正常输出,谢谢科普 ...
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1840 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 15:51 · PVG 23:51 · LAX 07:51 · JFK 10:51
    ♥ Do have faith in what you're doing.