I have found this answer to a seemingly similar issue, however (since I'm novice into Python) I am not sure how to implement this solution in my code (if it's the same issue after all).
In my code I have the following section:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
filename='C:\\Tests\\TRACE.log',
filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
consoleFormatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(consoleFormatter)
logging.getLogger('').addHandler(console)
localLog = logging.getLogger('text')
The funny thing is that it used to work fine but at some moment it started writing these duplicate messages to console.
Could someone give me a direction here please?
Python logging basicConfig The basicConfig configures the root logger. It does basic configuration for the logging system by creating a stream handler with a default formatter. The debug , info , warning , error and critical call basicConfig automatically if no handlers are defined for the root logger.
StreamHandler. The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).
Typically duplicate log statements occur because there are two separate handlers attached that are directing your log statements to the same place. There are a couple of things worth trying to get to the root of the problem:
To make your logging easier to manage, it may be worth looking to move the configuration out of the code and into a configuration file - the Python document on logging configuration is a great place to start.
It seems that I have figured out the source of this problem.
The thing is that I used to get logger at module level. It looked pretty logical but there is a pitfall – Python logging module respects all created logger before you load the configuration from a file. So basically, when I was importing a module(which uses gets logger internally) to a main code(where I was calling for a logger as well) it resulted in streaming the logger data twice.
The possible solutions to this problem are:
disable_existing_loggers
to False. Added since Python 2.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With