我有一個(gè)log.py模塊,該模塊至少在另外兩個(gè)模塊(server.py和device.py)中使用。它具有以下全局變量:fileLogger = logging.getLogger()fileLogger.setLevel(logging.DEBUG)consoleLogger = logging.getLogger()consoleLogger.setLevel(logging.DEBUG)file_logging_level_switch = { 'debug': fileLogger.debug, 'info': fileLogger.info, 'warning': fileLogger.warning, 'error': fileLogger.error, 'critical': fileLogger.critical}console_logging_level_switch = { 'debug': consoleLogger.debug, 'info': consoleLogger.info, 'warning': consoleLogger.warning, 'error': consoleLogger.error, 'critical': consoleLogger.critical}它具有兩個(gè)功能:def LoggingInit( logPath, logFile, html=True ): global fileLogger global consoleLogger logFormatStr = "[%(asctime)s %(threadName)s, %(levelname)s] %(message)s" consoleFormatStr = "[%(threadName)s, %(levelname)s] %(message)s" if html: logFormatStr = "<p>" + logFormatStr + "</p>" # File Handler for log file logFormatter = logging.Formatter(logFormatStr) fileHandler = logging.FileHandler( "{0}{1}.html".format( logPath, logFile )) fileHandler.setFormatter( logFormatter ) fileLogger.addHandler( fileHandler ) # Stream Handler for stdout, stderr consoleFormatter = logging.Formatter(consoleFormatStr) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter( consoleFormatter ) consoleLogger.addHandler( consoleHandler )和:def WriteLog( string, print_screen=True, remove_newlines=True, level='debug' ): if remove_newlines: string = string.replace('\r', '').replace('\n', ' ') if print_screen: console_logging_level_switch[level](string) file_logging_level_switch[level](string)我LoggingInit從調(diào)用server.py,它會(huì)初始化文件和控制臺(tái)記錄器。然后WriteLog,我從各地進(jìn)行呼叫,因此有多個(gè)線程正在訪問fileLogger和consoleLogger。我的日志文件是否需要任何進(jìn)一步的保護(hù)?文檔指出線程鎖由處理程序處理。
確保多個(gè)線程中的Python登錄是線程安全的
慕運(yùn)維8079593
2021-03-12 15:11:34