Python logger formatting is not formatting the string

2024/9/8 12:11:34

Following are the contents of mylogger.py:

def get_logger(name='my_super_logger'):log = logging.getLogger(name)log.setLevel(logging.DEBUG)formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')if not len(log.handlers):ch = logging.StreamHandler()ch.setLevel(logging.DEBUG)ch.setFormatter(formatter)log.addHandler(ch)# print(id(log))return log

and following is contents of myscript.py:

from mylogger import get_logger_logger = get_logger()_logger.info('trying info')
_logger.debug('trying debug')

However I am facing two issues. It prints the logs twice and formatter is not working everytime:

09/18/2015 09:59:54 PM my_super_logger trying info 
INFO:my_super_logger:trying info 
09/18/2015 09:59:54 PM my_super_logger trying debug 
DEBUG:my_super_logger:trying debug 

What exactly is the issue with my get_logger code?

I need a custom formatting. However I found out that without adding a handler I cannot add a formatter. So that's why I have added StreamHandler. And the reason for if block is mentioned in this answer. Without that, I would get duplicate log messages printed.

Answer

The root logger is also emitting the message. Stop propagation up to the root with:

log.propagate = False

If you wanted to format all log output (so messages propagated up to the logger), set the formatter for the root logger.

You can do so with a logging.basicConfig() call provided nothing has yet been sent to the loggers, or by looping over the logger.handlers list of the root logger; you could pick out any StreamHandlers if you so wish:

root_logger = logging.getLogger()  # no name
for handler in root_logger.handlers:if isinstance(handler, logging.Streamhandler):handler.setFormatter(formatter)
https://en.xdnf.cn/q/72644.html

Related Q&A

Python subprocess.Popen.wait() returns 0 even though an error occured

I am running a command line utility via Pythons subprocess module. I create a subprocess.Popen() object with the command line arguments and stdout=subprocess.PIPE and then I use subprocess.wait() to w…

Better way to call a chain of functions in python?

I have a chain of operations which needs to occur one after the other and each depends on the previous functions output.Like this:out1 = function1(initial_input) out2 = function2(out1) out3 = function3…

Pytest text annotation for test with tuple of parameters

Im looking for more elegant solution for this kind of problem:def ids(x):if isinstance(x, int):return str(x)elif isinstance(x, str):return x[0]@pytest.mark.parametrize("number, string",[(1, &…

OpenCV wont capture from MacBook Pro iSight

Since a couple of days I cant open my iSight camera from inside an opencv application any more. cap = cv2.VideoCapture(0) returns, and cap.isOpened() returns true. However, cap.grab() just returns fals…

SQLAlchemy filter on list attribute

I have the following model defined with Flask-SQLAlchemy:"""models.py"""from flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()skill_candidate = db.Table(SkillCandidate,d…

How to convert an InMemoryUploadedFile in django to a fomat for flickr API?

I have a class that uploads a file to Flickr. The file is of type InMemoryUploadedFile.I would like to know how to convert or pass the data in the InMemoryUploadedFile file, to a format for flickrs API…

Speed up Metropolis-Hastings algorithm in Python

I have some code that samples a posterior distribution using MCMC, specifically Metropolis Hastings. I use scipy to generate random samples:import numpy as np from scipy import statsdef get_samples(n):…

How to properly use Rules, restrict_xpaths to crawl and parse URLs with scrapy?

I am trying to program a crawl spider to crawl RSS feeds of a website and then parsing the meta tags of the article.The first RSS page is a page that displays the RSS categories. I managed to extract t…

sudo required for easy_install pip in OS X Lion?

Im coming from Snow Leopard at work to a Lion installation at home. I do NOT remember having to:sudo easy_install pipIs that required for Lion? I got errors until I did that, and pip ended up here:[…

CUDNN_STATUS_NOT_INITIALIZED when trying to run TensorFlow

I have installed TensorFlow 1.7 on an Ubuntu 16.04 with Cuda 9.0 and CuDNN 7.0.5 and vanilla Python 2.7 and although they samples for both CUDA and CuDNN run fine, and TensorFlow sees the GPU (so some …