问题
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