相关疑难解决方法(0)

Python 2.7:在两个python脚本中使用`logging`模块时,日志显示两次

语境:

Python 2.7.

同一文件夹中的两个文件:

  • 第一:主要脚本.
  • 第二:自定义模块.

目标:

可以在logging没有任何冲突的情况下使用模块(参见下面的输出).

文件:

a.py:

import logging
from b import test_b

def test_a(logger):
    logger.debug("debug")
    logger.info("info")
    logger.warning("warning")
    logger.error("error")

if __name__ == "__main__":
    # Custom logger.
    logger = logging.getLogger("test")

    formatter = logging.Formatter('[%(levelname)s] %(message)s')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)

    # Test A and B.
    print "B"
    test_b()
    print "A"
    test_a(logger)
Run Code Online (Sandbox Code Playgroud)

b.py:

import logging

def test_b():
    logging.debug("debug")
    logging.info("info")
    logging.warning("warning")
    logging.error("error")
Run Code Online (Sandbox Code Playgroud)

输出:

如下所示,日志显示两次.

python a.py
B
WARNING:root:warning
ERROR:root:error
A
[DEBUG] debug
DEBUG:test:debug
[INFO] info
INFO:test:info …
Run Code Online (Sandbox Code Playgroud)

python logging python-2.7

12
推荐指数
1
解决办法
8765
查看次数

标签 统计

logging ×1

python ×1

python-2.7 ×1