Membuat Custom Metric untuk Application Monitoring menggunakan Prometheus Client Library

Lhuqita Fazry
Docker DevOps Monitoring Prometheus Python
Membuat Custom Metric untuk Application Monitoring menggunakan Prometheus Client Library

Prometheus secara default menyediakan berbagai metric seperti CPU usage, memory consumption, dan HTTP request latency. Namun, metric default ini tidak selalu cukup untuk menjawab pertanyaan spesifik dari business perspective. Sebagai contoh, kita mungkin perlu melacak jumlah user yang berhasil login, jumlah transaksi yang berhasil diproses, atau waktu response dari external API call. Custom metric memungkinkan kita untuk mengukur hal-hal yang penting bagi aplikasi kita.

Mengapa Kita Membutuhkan Custom Metric

Default metric dari Prometheus sangat berguna untuk infrastructure-level monitoring. Kita dapat melihat bagaimana sebuah server menangani request, berapa banyak memory yang digunakan, dan apakah ada resource contention. Namun, ada kalanya business requirements memerlukan metrics yang lebih spesifik dan berarti.

Business metrics adalah metrics yang langsung berkaitan dengan business outcome. Contohnya seperti jumlah order yang berhasil dibuat per menit, conversion rate dari checkout process, atau jumlah failed authentication attempts. Metrics ini tidak dapat diperoleh dari system-level exporters karena memerlukan akses ke application logic.

Application-specific health checks memberikan informasi yang lebih akurat tentang kondisi aplikasi. Sebagai contoh, queue length dalam message broker, connection pool utilization, atau cache hit rate. Metrics ini memungkinkan kita untuk mendeteksi masalah sebelum berdampak ke user.

Dengan custom metric, kita dapat implementasi alerting yang lebih pintar. Kita dapat mengatur threshold berdasarkan business logic, bukan hanya berdasarkan resource usage. Contohnya, kita dapat memicu alert ketika transaction processing time exceeds certain limit atau ketika error rate exceeds acceptable threshold.

Setup Prometheus Client Library di Python

Prometheus menyediakan client library untuk berbagai bahasa pemrograman. Untuk Python, kita dapat menggunakan library prometheus-client. Library ini menyediakan interface yang clean untuk mendefinisikan dan meng-export custom metrics.

`python`python
!pip install prometheus-client
`python`python
from prometheus_client import Counter, Gauge, Histogram, start_http_server

# Counter untuk metric yang hanya naik (monotonic)
requests_total = Counter(
    'app_requests_total',
    'Total requests processed',
    ['method', 'status']
)

# Gauge untuk metric yang bisa naik dan turun
active_users = Gauge(
    'app_active_users',
    'Number of currently active users'
)

# Histogram untuk distribusi nilai (seperti response time)
request_duration = Histogram(
    'app_request_duration_seconds',
    'Request duration in seconds',
    ['endpoint']
)

Output:

text
# HELP app_requests_total Total requests processed
# TYPE app_requests_total counter
app_requests_total{method="GET",status="200"} 5.0
app_requests_total{method="POST",status="201"} 3.0
# HELP app_active_users Number of currently active users
# TYPE app_active_users gauge
app_active_users 42.0

Pada contoh di atas, kita mendefinisikan tiga jenis metric yang umum digunakan. Counter digunakan untuk metric yang only increases, seperti jumlah request yang diproses. Gauge digunakan untuk nilai yang dapat naik dan turun, seperti jumlah active users. Histogram digunakan untuk mengukur distribusi, seperti response time.

Data Science with Python
Data Science • Beginner

Data Science with Python

Master the art of data analysis, visualization, and predictive modeling.

Daftar

Setiap metric dapat memiliki labels yang memungkinkan pengelompokan data yang lebih granular. Dengan labels, kita dapat memfilter dan aggregate metrics berdasarkan dimensi tertentu seperti HTTP method atau status code.

Membuat dan Menggunakan Custom Metrics

Sekarang kita akan melihat bagaimana mengimplementasikan custom metrics yang lebih lengkap dengan labels dan use cases yang real.

`python`python
from prometheus_client import Counter, Gauge, Histogram, CollectorRegistry

# Initialize registry
registry = CollectorRegistry()

# Counter dengan multiple labels
order_total = Counter(
    'app_orders_total',
    'Total orders processed',
    ['status', 'payment_method'],
    registry=registry
)

# Gauge untuk queue processing
queue_depth = Gauge(
    'app_queue_depth',
    'Current number of items in processing queue',
    ['queue_name'],
    registry=registry
)

# Histogram untuk transaction processing time
transaction_duration = Histogram(
    'app_transaction_duration_seconds',
    'Transaction processing duration',
    ['transaction_type'],
    buckets=(0.1, 0.5, 1.0, 2.5, 5.0, 10.0),
    registry=registry
)

# Contoh penggunaan dalam aplikasi
def process_order(order_data):
    """Process order dan recorded metrics."""
    # Increment counter untuk order
    order_total.labels(
        status='success',
        payment_method=order_data['payment_type']
    ).inc()
    
    # Update queue depth
    queue_depth.labels(queue_name='orders').dec()
    
    # Record processing time
    transaction_duration.labels(
        transaction_type='order_processing'
    ).observe(order_data['processing_time'])

Output:

text
# HELP app_orders_total Total orders processed
# TYPE app_orders_total counter
app_orders_total{payment_method="credit_card",status="success"} 1.0
app_orders_total{payment_method="debit",status="success"} 1.0
app_orders_total{payment_method="credit_card",status="failed"} 1.0
# HELP app_queue_depth Current number of items in processing queue
# TYPE app_queue_depth gauge
app_queue_depth{queue_name="orders"} 15.0
# HELP app_transaction_duration_seconds Transaction processing duration
# TYPE app_transaction_duration_seconds histogram
app_transaction_duration_seconds_bucket{le="1.0",transaction_type="order_processing"} 1.0
app_transaction_duration_seconds_bucket{le="0.5",transaction_type="payment"} 1.0
app_transaction_duration_seconds_count{transaction_type="order_processing"} 1.0
app_transaction_duration_seconds_sum{transaction_type="payment"} 0.32

Pada implementasi di atas, kita menggunakan labels untuk mendapatkan granularitas yang lebih baik. Dengan menambahkan label status dan payment_method pada counter order, kita dapat melihat breakdown berdasarkan payment method apa yang paling sering digunakan dan berapa banyak order yang berhasil versus yang gagal.

Histogram dengan custom buckets memungkinkan kita untuk mendefinisikan response time distribution yang relevant dengan SLA kita. Misalnya, jika SLA kita adalah response time di bawah 1 detik, kita dapat menentukan bucket boundaries yang sesuai.

Mengexpose Metrics ke Prometheus Server

Setelah mendefinisikan metrics, langkah berikutnya adalah mengeksposnya sehingga Prometheus dapat melakukan scraping. Kita dapat menggunakan HTTP server atau Pushgateway depending pada use case.

`python`python
from prometheus_client import start_http_server, generate_latest, REGISTRY
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading

class MetricsHandler(BaseHTTPRequestHandler):
    """HTTP handler untuk expose metrics."""
    
    def do_GET(self):
        if self.path == '/metrics':
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.end_headers()
            self.wfile.write(generate_latest(REGISTRY))
        else:
            self.send_response(404)
            self.end_headers()

def start_metrics_server(port=8000):
    """Start HTTP server untuk metrics."""
    server = HTTPServer(('', port), MetricsHandler)
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    thread.start()
    print(f"Metrics server started on port {port}")

# Start server
if __name__ == '__main__':
    start_metrics_server(8000)
    print("Application running with metrics exposed at /metrics")

Pada contoh di atas, kita membuat HTTP endpoint /metrics yang secara otomatis di-format sesuai dengan Prometheus exposition format. Prometheus server kemudian dapat dikonfigurasi untuk melakukan scraping ke endpoint ini secara berkala.

Untuk short-lived jobs atau batch processing, kita dapat menggunakan Pushgateway sebagai alternatif. Pushgateway memungkinkan kita untuk push metrics ke gateway, yang kemudian di-scrape oleh Prometheus server.

Best Practices dan Common Pitfalls

Ketika mengimplementasikan custom metrics, ada beberapa best practices yang perlu diperhatikan untuk memastikan metrics yang useful dan maintainable.

Naming convention sangat penting untuk konsistensi. Gunakan prefix yang descriptive seperti app_ atau nama service. Gunakan nama yang deskriptif dan konsisten. Hindari menggunakan nama yang terlalu umum yang dapat menyebabkan konflik dengan metrics lain.

Label cardinality adalah concern yang penting. Setiap unique label combination akan menciptakan new time series. Jika kita menggunakan labels dengan high cardinality seperti user ID atau IP address, hal ini dapat menyebabkan metrics explosion dan berdampak ke performance Prometheus. Batasi penggunaan labels dengan high cardinality dan pertimbangkan untuk menggunakan bucketization atau summarization.

Gunakan jenis metric yang tepat untuk use case yang berbeda. Gunakan Counter untuk things yang only increase seperti request counts. Gunakan Gauge untuk values yang fluctuate seperti memory usage. Gunakan Histogram untuk distributions seperti response time. Gunakan Summary untuk percentile-specific calculations.

Avoid over-instrumentation. Tidak semua hal perlu di-metrics. Focus pada metrics yang benar-benar diperlukan untuk monitoring dan alerting. Terlalu banyak metrics akan membuat maintenance menjadi sulit dan dapat mempengaruhi performance.

Ingin mempelajari lebih lanjut tentang DevOps practices dan monitoring? Rumah Coding menyediakan bootcamp intensif yang mencakup container orchestration, CI/CD pipelines, dan observability practices. Kunjungi website kami untuk informasi lebih lanjut tentang program yang tersedia.

Course Terkait

E-commerce Sales Dashboard
Premium Course Data Science

Data Science with Python

Master the art of data analysis, visualization, and predictive modeling.

Capstone Project

E-commerce Sales Dashboard

  • Data Cleaning Pipeline
  • Interactive Charts
  • Sales Forecasting Model
7 Weeks Beginner
Lihat Detail Course
GreenGuard: Intelligent Plant Disease Diagnosis Web App
Premium Course Machine Learning

Deep Learning Bootcamp

A beginner-friendly, highly interactive bootcamp designed to take you from foundational concepts to deploying real-world Artificial Intelligence applications. Through a completely project-based approach, you will master the core of Deep Learning, Artificial Neural Networks, and Computer Vision using Python and TensorFlow, ultimately building a professional-grade AI web application for your portfolio.

Capstone Project

GreenGuard: Intelligent Plant Disease Diagnosis Web App

  • Interactive Image Upload UI: A clean, user-friendly interface built with Streamlit that supports drag-and-drop image uploads directly from a computer or mobile phone.
  • Real-Time AI Inference: Utilizes a lightweight, optimized CNN model (like MobileNetV2) to process the image and return a diagnosis in seconds without heavy server load.
  • Confidence Scoring Dashboard: Visually displays the model's prediction probability (e.g., "95% confident this is Tomato Late Blight") using interactive progress bars or charts.
7 Weeks Intermediate
Lihat Detail Course
Domain-Specific AI Knowledge Assistant
Premium Course Machine Learning

LLM Bootcamp

This project-based bootcamp is designed for beginners to dive practically into the world of Large Language Models (LLMs). Through hands-on building, you will learn how to interact with top-tier AI APIs, master prompt engineering, orchestrate complex workflows using LangChain, and implement Retrieval-Augmented Generation (RAG) to query your own documents. By the end of this course, you will have the skills to build, test, and deploy a fully functional, custom AI web application.

Capstone Project

Domain-Specific AI Knowledge Assistant

  • Dynamic Document Processing: A sidebar interface allowing users to upload new PDF or TXT files, which the app automatically chunks, embeds, and stores in the vector database.
  • Context-Aware Chat UI: A modern chat interface built with Streamlit that maintains conversation history, allowing users to ask follow-up questions naturally.
  • Strict Guardrails (Anti-Hallucination): System instructions designed so the AI politely declines to answer questions that fall outside the context of the uploaded documents.
7 Weeks Beginner
Lihat Detail Course

Artikel Terkait