KMG
KMG

Reputation: 927

Python logging adds duplicate entries

I am adding logging to my Python code. Messages are logged to the file correctly, but it's logging duplicate messages, like re-logging already logged entries to the file.

This is my code:

import logging

logger = logging.getLogger('Sample')
logger.setLevel(logging.DEBUG)

formatter =logging.Formatter('%(message)s')

handler=logging.FileHandler('./sample.log')

handler.setFormatter(formatter)

logger.addHandler(handler)


def add(x, y):
    return x + y

num_1=10
num_2=5 
add_result=add(num_1,num_2)
logger.debug("Result: %s "%add_result)

Output:

1st run : Single output

2nd run: Three output

3rd run: Six output

Upvotes: 0

Views: 325

Answers (1)

joergd
joergd

Reputation: 510

Try saving your script to a file test_log.py and then run python test_log.py from the terminal to start your script. This way, each run should always append a single log message to sample.log, as expected.

I guess you ran your code multiple times in an interactive python shell. The line logger.addHandler(handler) then always adds a new logging handler to your logger object, so that after running your code two times, you actually have two logging handlers that are both writing into your sample.log --> hence the duplicated entries.

Also, try changing your formatter to formatter = logging.Formatter('%(asctime)-15s %(message)s'). This will add a timestamp to your log messages (format year-month-day hour:minutes:seconds,milliseconds), allowing you to better debug your code.

Upvotes: 2

Related Questions