

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 监控 Python Managed Service for Apache Flink Python 应用程序
<a name="how-python-monitoring"></a>

您可以使用应用程序的 CloudWatch 日志来监视适用于 Apache Flink Python 应用程序的托管服务。

Managed Service for Apache Flink 记录 Python 应用程序的以下消息：
+ 在应用程序的`main`方法`print()`中使用写入控制台的消息。
+ 使用`logging`软件包在用户定义的函数中发送的消息。以下代码示例演示了如何通过用户定义的函数写入应用程序日志：

  ```
  import logging
  
  @udf(input_types=[DataTypes.BIGINT()], result_type=DataTypes.BIGINT())
  def doNothingUdf(i):
      logging.info("Got {} in the doNothingUdf".format(str(i)))
      return i
  ```
+ 应用程序抛出的错误消息。

  如果应用程序在`main`函数中抛出异常，它将出现在应用程序的日志中。

  以下示例演示了 Python 代码引发的异常的日志条目：

  ```
  2021-03-15 16:21:20.000   --------------------------- Python Process Started --------------------------
  2021-03-15 16:21:21.000   Traceback (most recent call last):
  2021-03-15 16:21:21.000   "  File ""/tmp/flink-web-6118109b-1cd2-439c-9dcd-218874197fa9/flink-web-upload/4390b233-75cb-4205-a532-441a2de83db3_code/PythonKinesisSink/PythonUdfUndeclared.py"", line 101, in <module>"
  2021-03-15 16:21:21.000       main()
  2021-03-15 16:21:21.000   "  File ""/tmp/flink-web-6118109b-1cd2-439c-9dcd-218874197fa9/flink-web-upload/4390b233-75cb-4205-a532-441a2de83db3_code/PythonKinesisSink/PythonUdfUndeclared.py"", line 54, in main"
  2021-03-15 16:21:21.000   "    table_env.register_function(""doNothingUdf"", doNothingUdf)"
  2021-03-15 16:21:21.000   NameError: name 'doNothingUdf' is not defined
  2021-03-15 16:21:21.000   --------------------------- Python Process Exited ---------------------------
  2021-03-15 16:21:21.000   Run python process failed
  2021-03-15 16:21:21.000   Error occurred when trying to start the job
  ```

**注意**  
由于性能问题，我们建议您在应用程序开发期间仅使用自定义日志消息。

## 使用 CloudWatch 见解查询日志
<a name="how-python-monitoring-insights"></a>

以下 CloudWatch Insights 查询会搜索在执行应用程序主函数时由 Python 入口点创建的日志：

```
fields @timestamp, message
| sort @timestamp asc
| filter logger like /PythonDriver/
| limit 1000
```