引言:为什么监控对 Kotlin 应用至关重要
运行在 JVM(Java 虚拟机)上的现代 Kotlin 应用,常常成为基础设施的关键节点。如果没有适当的监控,您可能会面临突然崩溃、内存泄漏或性能下降的风险,而这些在事故发生前往往难以察觉。本文将详细讲解如何构建一套完整的 Kotlin 应用监控系统「从 A 到 Z」:从收集基础指标(CPU、内存、GC)到在 Grafana 和 Prometheus 中配置告警。
我们将介绍三个关键工具:Micrometer(指标门面)、Prometheus(存储与采集器)和 Grafana(可视化与告警)。所有代码示例均使用 Kotlin 编写。
1. 指标收集基础:Micrometer 与 Prometheus
Micrometer 是 Spring 和 Kotlin 生态系统中事实上的标准监控门面。它提供统一的 API,用于将指标发送到各种系统(Prometheus、Datadog、New Relic 等)。
1.1. 添加依赖(Gradle)
dependencies { implementation("io.micrometer:micrometer-registry-prometheus:1.12.0") implementation("org.springframework.boot:spring-boot-starter-actuator")}对于 Ktor 或不含 Spring 的纯 Kotlin,可以仅添加 micrometer-core 和 micrometer-registry-prometheus。
1.2. Spring Boot 中 Micrometer 的基本配置
在 application.yml 中,只需启用 Actuator 和 Prometheus 端点:
management: endpoints: web: exposure: include: health,info,prometheus metrics: export: prometheus: enabled: true应用启动后,指标可通过 /actuator/prometheus 地址获取。
1.3. 创建自定义指标(Kotlin 示例)
假设您想要统计已处理的订单数量及其处理时间:
import io.micrometer.core.instrument.MeterRegistryimport io.micrometer.core.instrument.Timerimport org.springframework.stereotype.Serviceimport java.util.concurrent.atomic.AtomicLong
@Serviceclass OrderService(private val registry: MeterRegistry) {
private val processedOrders: AtomicLong = registry.gauge( "orders.processed.count", AtomicLong(0) ) private val orderProcessingTime: Timer = registry.timer("orders.processing.time")
fun processOrder(orderId: String) { val sample = Timer.start() try { // 订单处理逻辑 Thread.sleep((50..200).random().toLong()) processedOrders.incrementAndGet() } finally { sample.stop(orderProcessingTime) } }}现在,指标 orders_processed_count 和 orders_processing_time_seconds 将出现在 Prometheus 中。
2. 配置 Prometheus 收集指标
Prometheus 是一个服务器,它按照计划从您的应用中「抓取」(请求)指标。
2.1. prometheus.yml 配置
将您的 Kotlin 服务添加为目标:
scrape_configs: - job_name: 'kotlin-app' metrics_path: '/actuator/prometheus' static_configs: - targets: ['localhost:8080']如果应用运行在 Docker/Kubernetes 中,请使用服务发现。
2.2. 默认的重要 JVM 指标
Micrometer 会自动导出许多 JVM 指标:
jvm_memory_used_bytes— 已用内存(堆/非堆)jvm_gc_pause_seconds— GC 暂停时间jvm_threads_live_threads— 活跃线程数process_cpu_usage— 进程 CPU 使用率
这些数据在 Prome