append logs using 'filemode = a' does not work properly with python logger's fileHandler

随声附和 提交于 2019-12-11 16:37:58

问题


I want to append logs in two different logfiles using python logger fileHandler.

So, I created 2 different logger handlers(messaging_logger & payments_logger) handling logging in 2 files namely messaging.log & payments.log. I want that everytime I run this code , the log data I am writing in writemsg() & writepayent() should get appended in its respective log file. So,When I run the code for the first time , it logs data correctly. Then, in second time run , it does not seem to append the data correctly in both files. Please have a look at the code and output:

import logging

from logging import FileHandler
from logging import Formatter

LOG_FORMAT = (
            "%(asctime)s [%(levelname)s]: %(message)s")
LOG_LEVEL = logging.INFO

# messaging logger
MESSAGING_LOG_FILE = "messaging.log"


messaging_logger = logging.getLogger("messaging")
messaging_logger.setLevel(LOG_LEVEL)
```
messaging_logger_file_handler = FileHandler(MESSAGING_LOG_FILE,mode='a')
```
messaging_logger_file_handler.setLevel(LOG_LEVEL)
messaging_logger_file_handler.setFormatter(Formatter(LOG_FORMAT))
messaging_logger.addHandler(messaging_logger_file_handler)

# payments logger
PAYMENTS_LOG_FILE = "payments.log"
payments_logger = logging.getLogger("payments")

payments_logger.setLevel(LOG_LEVEL)
```
payments_file_handler = FileHandler(PAYMENTS_LOG_FILE,mode='a')
```
payments_file_handler.setLevel(LOG_LEVEL)
payments_file_handler.setFormatter(Formatter(LOG_FORMAT))
payments_logger.addHandler(payments_file_handler)

def writemsg():

    messaging_logger.info("Welcome to messages!")
    messaging_logger.info("This is message log!")

def writepayent():

    payments_logger.info("Welcome to payments!")
    payments_logger.info("This is paymentslog!")

writemsg()

writepayent()

E.g If I run above code in Spyder IDE for 2 times:

I expect output in messaging.log file as:

2019-04-16 16:23:28,759 [INFO]: Welcome to messages!

2019-04-16 16:23:28,762 [INFO]: This is message log!

2019-04-16 16:23:51,460 [INFO]: Welcome to messages!

2019-04-16 16:23:51,461 [INFO]: This is message log!

Actual Output I got :

2019-04-16 16:30:44,720 [INFO]: Welcome to messages!

2019-04-16 16:30:44,720 [INFO]: Welcome to messages!

2019-04-16 16:30:44,730 [INFO]: This is message log!

2019-04-16 16:30:44,730 [INFO]: This is message log!

Similar observation for payments.log

来源:https://stackoverflow.com/questions/55718051/append-logs-using-filemode-a-does-not-work-properly-with-python-loggers-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!