logging.config报错FileNotFoundError

本文记录了一次在Python项目中遇到的日志配置文件路径错误问题,错误信息为FileNotFoundError,具体原因是路径字符串中单引号与双引号的误用。通过修正路径字符串的引号类型,成功解决了这一看似简单实则困扰的问题。

FileNotFoundError: [Errno 2] No such file or directory: 'E:\\Githubresponsity\\weibo1123\\log\\info.log'

logging.config.fileConfig("E:\Githubresponsity\weibo1123\step5_LDA\logging.conf")

错误竟然是,单引号与双引号,我晕,这个错误也太狗血了

将下列代码报错的日志进行保存ef get_image(): try: # 清理上传目录中的JPEG文件 for filename in os.listdir(uploads_path): if filename.endswith('.jpg'): file_path = os.path.join(uploads_path, filename) os.remove(file_path) # 简化删除逻辑,异常将被外层捕获 # 重置全局状态 global RESET_TIME RESET_TIME = True # 获取并验证JSON数据 json_data = request.get_json() if not json_data or 'data' not in json_data or 'data' not in json_data['data']: logging.error("无效的JSON格式:缺少'data.data'字段") raise ValueError("无效的JSON格式:缺少'data.data'字段") up_file = json_data["data"]["data"] saved_images = [] # 处理每个上传的图像 for image_id, value in up_file.items(): # 安全过滤图像ID,只保留字母数字和部分安全字符 safe_id = ''.join(e for e in image_id if e.isalnum() or e in ['_', '-']) if not safe_id: logging.error(f"Invalid image ID: {image_id}") raise ValueError(f"Invalid image ID: {image_id}") up_filename = safe_id + ".jpg" save_file = os.path.join(uploads_path, up_filename) # 解码Base64数据 try: image_data = base64.b64decode(value) except (base64.binascii.Error, TypeError) as e: logging.error(f"ID为{safe_id}的图像数据解码失败: {str(e)}") raise ValueError(f"ID为{safe_id}的图像数据解码失败: {str(e)}") # 打开并验证图像 try: image = Image.open(BytesIO(image_data)) image.verify() # 验证图像完整性 image = Image.open(BytesIO(image_data)) # 验证后重新打开 except UnidentifiedImageError as e: logging.error(f"图像破损 ID {safe_id}: {str(e)}") raise ValueError(f"图像破损 ID {safe_id}: {str(e)}") except Exception as e: logging.error(f"Failed to process image ID {safe_id}: {str(e)}") raise ValueError(f"Failed to process image ID {safe_id}: {str(e)}") # 保存图像 try: image.save(save_file) except Exception as e: logging.error(f"Failed to save image ID {safe_id} to {save_file}: {str(e)}") raise ValueError(f"Failed to save image ID {safe_id} to {save_file}: {str(e)}") saved_images.append((safe_id, save_file)) # 检查是否有成功保存的图像 if not saved_images: logging.error("没有图像被成功处理") raise ValueError("没有图像被成功处理") return saved_images[-1][0], saved_images[-1][1] except Exception as e: logging.error(f'Critical error in get_image: {str(e)}') # 可以在这里添加更多的错误日志记录 print(f'Critical error in get_image: {str(e)}') raise # 重新抛出异常,让调用者处理 @app.route("/api/YuHangAI/picture/v2.0/",methods=['GET','POST']) def interface_usage(): message = """<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>北京御航智能</title> </head> <body> <h1>北京御航智能图像智能识别服务接口</h1> <p>提供多种场景下的图像识别</p> </body> </html>""" return message # 输电识别模型, 无人机巡检场景 @app.route("/api/YuHangAI/picture/v2.0/transmission",methods=['POST']) def detect_transmission_image(): logger.info("输电缺陷识别") start_time = time.time() json_data = request.get_json() try: _type = json_data["type"] except: _type = False image_id, save_file = get_image() time_1 = time.time() logger.info(f"处理数据用时{time_1-start_time}s") print(f"处理数据用时",file = sys.stderr) if save_file is None: logging.error('不支持的图像类型!') return jsonify("不支持的图像类型!") try: if _type == "wrjwyy": out_json = {"results":[]} out_json["data"]=preprocessing(save_file) else: out_json = {'image_id':image_id} objects = pool.apply_async(func=detect_transmission_models,args=(save_file,)).get() # result = pool.apply_async(func=detect_transmission_models, args=(save_file,)) # objects = result.get(timeout=30) count = 0 if len(objects) > 0: for key, values in objects.items(): if _type == "wrjwyy": if key in name_map: for value in values: if value[4] > 0.7: value.append(name_map[key]) out_json["results"].append({"result":value}) else: for value in values: if value[4] < 0.7: continue value.append(key) out_json[str(count)] = {"result":value} count += 1 except torch.cuda.OutOfMemoryError: logging.error("CUDA内存不足错误") out_json['status'] = '检测任务失败:GPU内存不足' except FileNotFoundError: logging.error(f"文件不存在: {save_file}") out_json['status'] = '检测任务失败:文件不存在' except Exception as e: import traceback logging.error(traceback.format_exc()) out_json['status'] = '检测任务失败!'+str(e) logging.error('检测任务失败!'+str(e)) time_2 = time.time() logger.info(f"检测图片用时{time_2-time_1}s") # print(f'检测图片用时{time_2-time_1}s',file = stdout) try: os.remove(save_file) except Exception as e: # logger.info('Failed to delete %s. Reason: %s' % (save_file, e)) print('Failed to delete %s. Reason: %s' % (save_file, e)) return jsonify(out_json)
08-07
Traceback (most recent call last): File "/Users/qingshan/workplace/nparks-fccs-service/env/bin/uvicorn", line 8, in <module> sys.exit(main()) ^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/click/core.py", line 1161, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/click/core.py", line 1082, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/click/core.py", line 1443, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/click/core.py", line 788, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/uvicorn/main.py", line 418, in main run( File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/uvicorn/main.py", line 522, in run config = Config( ^^^^^^^ File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/uvicorn/config.py", line 276, in __init__ self.configure_logging() File "/Users/qingshan/workplace/nparks-fccs-service/env/lib/python3.11/site-packages/uvicorn/config.py", line 400, in configure_logging logging.config.fileConfig( File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/config.py", line 90, in fileConfig handlers = _install_handlers(cp, formatters) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/config.py", line 156, in _install_handlers h = klass(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/handlers.py", line 214, in __init__ BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding, File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/handlers.py", line 58, in __init__ logging.FileHandler.__init__(self, filename, mode=mode, File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/__init__.py", line 1181, in __init__ StreamHandler.__init__(self, self._open()) ^^^^^^^^^^^^ File "/usr/local/Cellar/python@3.11/3.11.12/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/__init__.py", line 1213, in _open return open_func(self.baseFilename, self.mode, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: '/Users/qingshan/workplace/nparks-fccs-service/logs/uvicorn.log' 但是报错
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值