惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
博客园 - 司徒正美
美团技术团队
Martin Fowler
Martin Fowler
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
博客园 - 三生石上(FineUI控件)
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
U
Unit 42
Y
Y Combinator Blog
月光博客
月光博客
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
GbyAI
GbyAI
H
Help Net Security
量子位
Last Week in AI
Last Week in AI
博客园_首页
腾讯CDC
小众软件
小众软件

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
Duplicate Logging Messages in Python
2020-06-20 · via jdhao's digital space

When I am working on a project, I find that the same message is printed twice. The following minimal code can reproduce this issue:

Source code for logger.py:

import sys
import logging


class MyLogger:
    def __init__(self, name):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)

        stream_handler = logging.StreamHandler(sys.stderr)
        formatter = logging.Formatter(
            "[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S"
        )
        stream_handler.setFormatter(formatter)

        stream_handler.setLevel(logging.DEBUG)
        self.logger.addHandler(stream_handler)
        # self.logger.propagate = False

    def info(self, message):
        self.logger.info("{}".format(message))

my_logger = MyLogger("Logging debug")

Source code for main.py:

import logging

from logger import my_logger

root_logger = logging.getLogger()
stream_handler = logging.StreamHandler()
root_logger.addHandler(stream_handler)

my_logger.info("demo")
my_logger.info("another test")

When we run main.py, we can see that each log message is printed twice on the console:

[2020-06-19 21:56:53] [Logging debug] [INFO] demo
demo
[2020-06-19 21:56:53] [Logging debug] [INFO] another test
another test

But why? The reason is that, when we use logging.getLogger() without any argument, we will get the root logger. my_logger in logger.py is thus a child logger of this root logger. By default, child logger messages will be propagated to the logger in the upper hierarchy.

We have two options: (1) Disable propagation from child logger (2) Do not use root logger.

Option 1: In the logger.py, uncomment the line self.logger.propagate = False to make sure that child logger does not propagate its message to the root logger.

Option 2: Simply do not use root logger in main.py. For example, we can get another logger by using another_logger = logging.getLogger('main'). In this way, logging message from my_logger have no relationship with another_logger. So the logging messages are printed only once.

References#