如何为Ballerina自定义函数选择性添加可观测性?
在Ballerina中为普通函数开启可观测性的方法
Ballerina支持为普通函数选择性开启可观测性,主要有两种实现方式:
1. 使用@observable注解
直接给目标函数添加@observable注解,即可手动开启该函数的指标与追踪监控能力。Ballerina会自动为函数生成调用次数、耗时等指标数据,以及完整的追踪链路信息。
示例代码:
import ballerina/log; @observable function calculateTotal(int[] items) returns int { int total = 0; foreach int item in items { total += item; } log:printInfo("Calculated total: " + total.toString()); return total; } public function main() { int[] values = [10, 20, 30]; int result = calculateTotal(values); log:printInfo("Final result: " + result.toString()); }
2. 通过Ballerina.toml配置观测规则
如果需要批量管理多个函数的可观测性,或精细控制观测行为,可以在项目根目录的Ballerina.toml中配置观测规则。可指定包、模块或特定函数的观测开关,还能自定义指标名称、追踪采样率等参数。
示例配置:
[observability] enabled = true [observability.rules."custom-function-rule"] package = "your.package.path" functions = ["calculateTotal", "processUserInput"] metricsEnabled = true tracingEnabled = true
注意事项
- 需使用Ballerina 2201.4.0及以上版本,
@observable注解在该版本及之后稳定支持。 - 开启可观测性后,需正确配置数据导出(如Prometheus导出指标、Jaeger导出追踪数据),才能在监控系统中查看对应数据。
内容的提问来源于stack exchange,提问作者Gabil
相关产品推荐
相关产品推荐

