You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加日志转发后Digital Ocean Function返回通用错误代码

Digital Ocean App Platform添加Logtail日志转发后Python数据库连接函数异常

我在Digital Ocean App Platform中测试一个简单的Python函数,功能是导入psycopg2并连接关联的Postgres数据库,返回数据库版本。该函数原本运行正常,但为DO应用及函数添加日志转发至Betterstack(Logtail)后出现异常。

添加日志转发的原因:DO官方支持确认,若函数为独立函数,仅能通过命令行工具doctl查看日志;若函数属于应用的一部分,则需将日志转发至外部日志服务。我在平台内无法直接获取函数日志,所以配置了Logtail转发。

正常返回结果

原本函数会返回成功消息:

{
  "message": "Successfully imported dependencies and found DB version RealDictRow([('version', 'PostgreSQL 16.9 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 14.2.1 20240912 (Red Hat 14.2.1-3), 64-bit')]).",
  "psycopg2_version": "2.9.10 (dt dec pq3 ext lo64)"
}

异常返回结果

现在函数不再返回成功消息,而是返回Digital Ocean抛出的通用错误:

{
"code": "abc123581b123ea5e3d73848",
"error": "There was an error processing your request."
}

项目配置(project.yml)

根据DO支持建议配置的LOG_DESTINATIONS:

environment:
  DB_HOST: "${DB_HOST}"
  DB_PORT: "${DB_PORT}"
  DB_USER: "${DB_USER}"
  DB_PASSWORD: "${DB_PASSWORD}"
  DB_NAME: "${DB_NAME}"
  DB_SSL_MODE: "${DB_SSL_MODE}"
  LOG_DESTINATIONS: "[{'logtail':{'token':'${LOGTAIL_TOKEN}'}}]"
packages:
  - name: db-test
    actions:
      - name: db-tester
        runtime: 'python:default'
        web: true

Python函数代码

import os
import psycopg2
from psycopg2.extras import RealDictCursor

def get_db_connection():
    """Create a connection to the PostgreSQL database"""
    print("Connecting to the database...")
    connection = psycopg2.connect(
        host=os.environ.get("DB_HOST"),
        port=os.environ.get("DB_PORT"),
        dbname=os.environ.get("DB_NAME"),
        user=os.environ.get("DB_USER"),
        password=os.environ.get("DB_PASSWORD"),
        sslmode=os.environ.get("DB_SSL_MODE"),
        cursor_factory=RealDictCursor
    )
    return connection

def main(args):
    try:
        print("Starting the receipt-submitter function...")
        version = psycopg2.__version__
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT version();")
        db_version = cursor.fetchone()
        cursor.close()
        conn.close()

        # Test imports were successful
        return {
            "body": {
                "message": f"Successfully imported dependencies and found DB version {db_version}.",
                "psycopg2_version": version
            }
        }
    except Exception as e:
        print("Exception thrown.")
        return {
            "body": {
                "error": f"{str(e)}"
            },
            "statusCode": 500
        }

内容的提问来源于stack exchange,提问作者j3py

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:05:13