pythonloggingcomputer-visionyolov5

Python logging breaks after using YOLOv5


I am using logging module in the standard python library to save some data related to image processing in the file. The following code works correctly and prints the message in the file only. Nothing is printed in the console.

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('logfile.log')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s'))
if logger.hasHandlers():
    logger.handlers.clear()
logger.addHandler(file_handler)
logger.info('Processing image 1.')

However, if I modify it slightly so that it also uses YOLOv5 model after it, then the logging information will be written both to the file and the console.

import logging
import torch

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('logfile.log')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s'))
if logger.hasHandlers():
    logger.handlers.clear()
logger.addHandler(file_handler)
logger.info('Processing image 1.')

MODEL_WEIGHTS = 'runs/yolov5/train/exp4/weights/best.pt'
model = torch.hub.load('../YOLO/yolov5', 'custom', path=MODEL_WEIGHTS, source='local')

logger.info('Processing image 2.')

The first message related to image 1 is written to the file only, while the second message related to the image 2 gets printed in the file and the standard output. The output looks like this:

In [1]: runfile('/home/aleksandar/Documents/image_processing.py', wdir='/home/aleksandar/Documents')
YOLOv5 🚀 2022-5-27 Python-3.10.6 torch-1.13.0 CUDA:0 (Quadro RTX 5000, 16125MiB)

Fusing layers... 
Model summary: 367 layers, 46151358 parameters, 0 gradients
Adding AutoShape... 
Processing image 2.

How can I prevent this and not have log message printed in the console. They should be in the file only?


Solution

  • The issue you are facing is that YOLOv5's code modifies the root logger's configuration, which causes your subsequent log messages to also be printed to the console. To prevent this, you can isolate your logger from the root logger as follows:

    logger.propagate = False