current position:Home>How does Python prevent multiple logs under the same file from writing to one file at the same time

How does Python prevent multiple logs under the same file from writing to one file at the same time

2022-02-02 22:13:29 CSDN Q & A

For the convenience of management , I wrote several in one folder log example , Call whatever script you want to use , As a result, all instances are written into only one instance . Do you know what's going on with this thing

#!/usr/bin/env python# -*- coding: utf-8 -*-import loggingimport logging.handlersMAX_SIZE = 1024 * 1024 * 5   #  Single log Maximum file size MAX_NUMB = 10                #  The maximum number that can exist , After exceeding, the previous will be overwritten log file Level = { 0:logging.DEBUG, 1:logging.INFO, 2:logging.WARNING, 3:logging.ERROR, 4:logging.CRITICAL }class Log:    __file = None    __handler = False    __fmt = '%(asctime)s [%(filename)s](%(levelname)s) - %(message)s'    def __init__(self, logname="log.log"):        self.__file = logname        logging.basicConfig(filename=self.__file, filemode='a+', format=self.__fmt)        self.__handler = logging.handlers.RotatingFileHandler(self.__file, maxBytes=MAX_SIZE, backupCount=MAX_NUMB)        #  Print to console display         self.__handler = logging.StreamHandler()        self.__handler.setLevel(logging.INFO)        # Format         formatter = logging.Formatter(self.__fmt)        self.__handler.setFormatter(formatter)    # Get instance     def getInstance(self, strname="log", setlevel=0):        logger = logging.getLogger(strname)        logger.addHandler(self.__handler)        logger.setLevel(Level[setlevel])        return logger

Code management files

#!/usr/bin/env python# -*- coding: utf-8 -*-from Log  import LogTest_1_Log = Log(logname="../Log/test_1.log").getInstance("test_1", setlevel=2)Test_2_Log = Log(logname="../Log/test_2.log").getInstance("test_2", setlevel=2)Test_3_Log = Log(logname="../Log/test_3.log").getInstance("test_3", setlevel=1)

The expectation is Conduct importTest_1_Log Post inhalation test_1.log, Load write file test_2.log. But the result is that all files are written test_1, If Test_1_Log Follow Test_2_Log The swap will be written in full test_2.log ...
After checking up for a long time, I didn't find the result , Should not be getLogger Are there different files with different names ? Why is it so

Refer to the answer 1:

You instantiate one log That's it , Then set the instanced object properties as needed

Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.

Random recommended