from cloudsync.handlers.error import Error from cloudsync.utils.helpers import * from cloudsync.utils.globals import * from logging.handlers import TimedRotatingFileHandler class CustomTimedRotatingFileHandlerHandler(TimedRotatingFileHandler): """ Handler for logging to a file, rotating the log file and uploading it to cloud at certain timed intervals. It extends the official TimedRotatingFileHandler to add the upload functionality. """ def __init__(self, filename, prelogger: Logger, *args, **kwargs): super().__init__(filename, *args, **kwargs) self.network_request_handler = None self.error_handler = None self.g_config = None prelogger.info("CUSTOM LOG HANDLER INITIATED") def doRollover(self): super().doRollover() self.__select_files_to_upload() def set_network_provider(self, network_request_handler): self.network_request_handler = network_request_handler def set_error_provider(self, error_handler): self.error_handler = error_handler def set_configuration(self, g_config): self.g_config = g_config def __select_files_to_upload(cls): """ Checks for existing rotated files in the directory (excluding the newly created one) and uploads them. """ # We use the cls.baseFilename because according to code documentation: # the filename passed in, could be a path object (see Issue #27493), # but cls.baseFilename will be a string existing_files = [] base_name = os.path.basename(cls.baseFilename) for filename in os.listdir(os.path.dirname(cls.baseFilename)): if filename.startswith(base_name) and filename != base_name: existing_files.append(os.path.join(os.path.dirname(cls.baseFilename), filename)) if len(existing_files) > 0: for existing_file in existing_files: cls.__upload_cs_log_file(existing_file) def __upload_cs_log_file(cls, log_file_path): cs_log_data = { "path": log_file_path, "serialNumber": cls.g_config[CONFIG_DEVICE][CONFIG_DEVICE_HD_SERIAL], "checksum": helpers_sha256_checksum(log_file_path) } g_utils.logger.debug("CS log data: {cs_log_data}") try: helpers_add_to_network_queue(network_request_handler=cls.network_request_handler, request_type=NetworkRequestType.CS2DCS_REQ_SEND_CS_LOG, url='', payload=cs_log_data, method='', g_config=cls.g_config, success_message='CS2DCS_REQ_SEND_CS_LOG request added to network queue') except Exception as e: error = Error.general(OutboundMessageIDs.CS2UI_ERROR.value, ErrorIDs.CS_LOG_ERROR.value, str(e)) cls.error_handler.enqueue_error(error=error)