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
lvii
V2EX  ›  Python

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

  •  
  •   lvii · 2013-03-06 19:54:18 +08:00 · 4175 次点击
    这是一个创建于 4078 天前的主题,其中的信息可能已经有所发展或是发生改变。
    $ 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 条回复    1970-01-01 08:00:00 +08:00
    xuwenbao
        1
    xuwenbao  
       2013-03-07 08:57:59 +08:00   ❤️ 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
        2
    lvii  
    OP
       2013-03-08 11:22:59 +08:00
    @xuwenbao 兄,修改为 logger 对象后,可以输出日志到文件,但是只有 warning 日志
    debug 和 info 没有,修改日志级别为 DEBUG 后,debug 和 info 正常输出,谢谢科普 ...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2858 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:20 · PVG 22:20 · LAX 07:20 · JFK 10:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.