💻
Cheet Sheets
  • 🦁Başlarken
  • 🟧DevOps Pre-Requisite
    • ❤️Why Linux? | Linux Basics #1
    • 💛Vi Editor | Linux Basics #2
    • 💙Basics Commands | Linux Basics #3
    • 🧡Package Managers | Linux Basics #4
    • 💚Services | Linux Basics #5
    • 💛Networking Basics
    • 🤎DNS Basics
    • 🩶Applications Basics
    • 🟨Java introduction
    • 🟩NodeJS Introduction
    • 🟦Python Introduction
    • 🟪GIT Introduction
    • 🟧Apache Web Server Introduction
    • ⬛Apache Tomcat
    • 🟫Python Flask
    • 🟥Node.js Express App
    • 🟨Databases
    • 🟩MySQL
    • 🟪MongoDB
    • 🟨SSL & TLS
    • 🟦YAML & JSON - JSON Path
    • ⬛Labs Resources
  • 🍎Kubernetes
    • 🍏Kubernetes: Nedir ?
    • 🍒Bileşenler
    • 🍵Kubectl ve Versiyon
    • ❤️Pod
    • 🏷️Label ve Selector
    • 🔎Annotation
    • 📲Namespaces
    • 📦Deployments
    • 🔁ReplicaSet
    • 🔙Rollout & Rollback
    • 🌐Networking - 1
    • 🌏Service
    • 🛠️Liveness Probe & Readiness Probe
    • 🥐Resource Limits
    • 💰Environment Variables
    • 📃Ephemeral Volumes
    • 🔑Secrets
    • 🌂ConfigMap
    • 🖥️Node Affinity
    • 🔌Pod Affinity
    • ✍️Taint and Toleration
    • 🔦DaemonSet
    • 🧀PV/PVC
    • 🌜Storage Class
    • 🗿StatefulSet
    • 🕹️Job & Cronjob
    • 🔐Authentication
    • 📏Role-based access control (RBAC)
    • 🈷️Service Account
    • 📈Ingress
    • 📂ImagePullPolicy & ImageSecret
    • 📖Static Pods
    • 🌐Network Policy
    • 🫐Helm Nedir?
    • 📽️Prometheus Stack - Monitoring
    • 💼EFK Stack - Monitoring
    • 🥳CRD & Operator
  • 🧑‍⚕️GIT & GITHUB
    • 👉Girizgah
    • 🌴Branch
    • 🤝Merge
    • 🤔Conflict - Rebase
    • 🇸🇴Alias
    • 🛑Gitignore
    • 🥢Diff
    • ◀️Checkout
    • 🔦Stash
    • 👉Other
  • ☁️AWS
    • 🪣S3
    • 🚙EC2
    • ⚖️ELB
    • 🤝Auto Scaling
    • 🗄️EFS
    • 🔐VPC
    • 🎆CloudFront
    • ❤️Route53
    • 🦈RDS
    • 🏢ElastiCache
    • 🔭CloudWatch
    • 👀CloudTrail
    • 📃CloudFormation
    • 🔕SNS
    • 📬SQS
    • 🎇SWF
    • 📧SES
    • 📦Kinesis
    • 📐AWSConfig
    • 👩‍🏭OpsWork
    • 🚀Lambda - Api Gateway
    • 📌ECS - EKS
    • 🔑KMS
    • 📂Directory Service
    • 🏐Snowball
    • 💾Storage Gateway
    • 💽Volume Gateway
    • 📼Tape Gateway
    • 🏠Organizations
    • 🔙Backup-Transfer-CloudShell
    • 🆔IAM
    • 📀DataSync
    • 🗃️FSx
    • 🎒Aurora Serverless
    • 🌐Global Accelerator
    • 💪HPC
    • 🎰Outposts
    • 🗼Others
  • 👨‍🔬Ansible
    • 👉Girizhah
    • 📔YAML
    • ⚙️Komponentler
    • 🎒Inventory
    • 🏑ad-hoc
    • ▶️Playbook
  • 👨‍⚕️PROMETHEUS
    • 📈Terminoloji
    • 🦯Ubuntu 20.04 Prometheus Kurulum
    • 🗒️prometheus.yml dosyasına ilk bakış:
    • 🧭promQL up query
    • 📇Exporters
    • 🔦promQL Data Types
    • 🦯Selectors & Matchers
    • 🔢Binary Operators
    • 💀ignoring and on
    • ✍️Aggregation Operators
    • 🧠Functions
    • 🖊️Alıştırma
    • 💻Client Libraries
    • 🐍Examining the data of our Python application
    • 🐐Examining the data of our GO application
    • ⏺️Recording Rules
    • 💡rate functions
    • ⏰Alerting
    • ⌚Alert Routing
    • ⏰Slack integration with Prometheus
    • 🤯PagerDuty integration with Prometheus
    • ◼️BlackBox exporter
    • 📍Push Gateway
    • 🪒Service Discovery
    • 🧊kube cadvisor with external prometheus
    • 👉aws with prometheus
    • ☁️CloudWatch Exporter
    • 👨‍🚒mysql exporter
    • 🛃Custom exporter with Python
    • ⚙️Prometheus with HTTP API
    • 🤖Prometheus Federation For Kubernetes
    • 📺Grafana
    • ⁉️Prometheus: Ne zaman kullanılmalı? Ne zaman kullanılmamalıdır?
  • 🍪Sheets
    • 🛳️Docker Sheets
    • 🐐Kube Sheets
  • 🔢12 Factor APP
    • 🏗️Introduction
    • 1️⃣Codebase
    • 2️⃣Dependencies
    • 3️⃣Concurrency
    • 4️⃣Processes
    • 5️⃣Backing Services
    • 6️⃣Config
    • 7️⃣Build, release, run
    • 8️⃣Port binding
    • 9️⃣Disposability
    • 🔟Dev/prod parity
    • 🕚Logs
    • 🕛Admin processes
  • ☁️Azure 104
    • 👨‍👨‍👧‍👧Azure Active Directory ( Entra ID )
    • 💰Subscriptions
    • 🌎Virtual Network (VNET)
    • 💻Virtual Machines
    • 🧑‍🌾Load Balancing
    • 🥍Network Advanced
    • 🪡Automating Deployment and Configuration
    • 💂Securing Storage
    • 📓Administering Azure Blobs and Azure Files
    • 🔧Managing Storage
    • 🎁App Service
    • 🛳️Azure Container
    • 🥇Backup And Recovery
    • 🪐Network Watcher
    • ⏰Resource Monitoring And Alerts
  • ⛅AZURE 305
    • 🆔identity and access management
    • 💼Desing Azure AD (Entra ID)
    • 👨‍💼Desing for Azure B2B
    • 🛃Desing for Azure B2C
    • 💳Design for MFA and Conditional Access
    • ⛑️Design for Identity Protection
    • 🚶Access Reviews
    • 🚦Managed identity Demostration
    • 🔐Key Vault Demostration
    • 👑Governance hierarchy
    • 💠Design for Management Groups
    • 🔑Desing for Subscriptions
    • 🍇Desing for resource groups
    • 📟Design for resource tags
    • 🚷Azure Policy & RBAC
    • 🫐Desing For Blueprints
    • 🪡Desing for Virtual Networks
    • 🛫Design for on-premises connectivity to Azure
    • 🔽Design for network connectivity
    • 📦Design for application delivery
    • 🥞Design for network security and application protection
    • 📕Choose a compute solution
    • 🌊Design for virtual machines
    • 🔋Azure Batch Demostration
    • 🛰️Design for Azure App Service
    • ⛲Design for Azure Container Instances
    • 🎢Design for Azure Kubernetes Service
    • 📠Azure Functions Demostration
    • 💪Azure Logic Apps Demostration
    • 🧑‍💼Design for data storage
    • 🎞️Design for Azure storage accounts
    • 🌟Choose the storage replication
    • 📹Azure blob storage - Lifecycle & immutable demo
    • 🥌Azure Files Demostration
    • 🕸️Design Azure disks
    • 🦼Design for storage security
    • 🔮Azure Table Storage And Cosmos DB Demostration
    • 🟧Azure SQL Solutions
    • 🎡Azure SQL Database - Purchasing models
    • 🕯️Database availability
    • 📜Data security strategy
    • 🧮Azure SQL Edge
    • 🚲Azure Data Factory
    • 🔅Azure Data Lake Storage
    • 🧘‍♂️Azure Databricks
    • 🎒Azure Synapse Analytics
    • 🅰️Azure Stream Analytics
    • 📼Data flow strategy
    • 🍥Cloud Adoption Framework
    • ☣️Azure Migration Framework
    • 🦿Assessing workloads
    • 🪡Migration tools
    • 🤖Azure Database migration
    • 👥Storage migration
    • 👜Azure Backup
    • ⏲️Azure Blob Backup and Recovery
    • 💈Azure files backup and recovery
    • 🎞️Azure VM backup and recovery
    • 🧺Azure SQL backup and recovery
    • ⏰Azure Site Recovery
    • 📩Differentiate event and message
    • ✈️Azure messaging solutions
    • 🚜Event Hub
    • 🥍Application optimization solution
    • 🎁Application lifecycle
    • 📺Azure Monitor
    • 🅱️Log Analytics
    • 👥Azure workbooks and Insights
    • 🚌Azure Data Explorer
  • Github Actions
    • Github Actions Nedir?
    • Workflow & Schedule Triggers
    • Single and Multiple Events
    • Manuel Events
    • Webhook Events
    • Conditional Keywords For Steps
    • Expressions - 1
    • Expressions - 2
    • Runners
    • Workflow Commands
    • Workflow Context
    • Dependent Jobs
    • Encrypted Secrets
    • Configuration Variables
    • Default & Custom Env Varb
    • Set Env Varb with Workflow Commands
    • Github Token Secret
    • Add Script to workflow
    • Push Package #1
    • Push Package #2 Docker
    • Service Containers
    • Routing workflow to runner
    • CodeQL Step
    • Caching Package and Dependency Files
    • Remove workflow Artifact
    • Workflow Status Badge
    • Env Protection
    • Job Matrix Configuration
    • Disable & Delete Workflows
    • Actions type for Action
    • Inputs and Outputs for actions
    • Action Versions
    • Files and Directories for Actions
    • Exit Codes
    • Reusable Workflow & Reuse Templates for Actions and Workflows
    • Configure Self Hosted Runners for Enterprise
  • Loki
    • What is Loki?
    • Architecture of Loki
    • Install Loki For Ubuntu
    • Install Promtail For Ubuntu
    • Querying Logs
    • Loki in Kubernetes
    • Deploying Loki in Kubernetes
    • Connecting to Grafana
    • Viewing Kubernetes logs
    • Promtail Customize & Pipeline
  • Ansible
    • Ansible Introduction
    • Introduction to Ansible Configuration Files
    • Ansible Inventory
    • Inventory Formats
    • Ansible Variables
    • Variable Types
    • Registering Variables and Variable Precedence
    • Variable Scoping
    • Magic Variables
    • Ansible Facts
    • Ansible Playbooks
    • Verifying Playbooks
    • Ansible lint
    • Ansible Conditionals
    • Ansible Conditionals based on facts, variables, re-use
    • Ansible Loops
    • Ansible Modules
    • Introduction to Ansible Plugins
    • Modules and Plugins Index
    • Introduction to Handlers
    • Ansible Roles
    • Ansible Collections
    • Introduction to Templating
    • Jinja2 Templates for Dynamic Configs
  • 🅰️Ansible Advanced
    • Playbook run options
    • Facts
    • Configuration files
Powered by GitBook
On this page

Was this helpful?

  1. PROMETHEUS

Examining the data of our GO application

Counter Metrics

package main

import (
        "net/http"
        "fmt"
        "log"
        "github.com/gorilla/mux"
        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "github.com/prometheus/client_golang/prometheus/promauto"
)

var
        REQUEST_COUNT = promauto.NewCounter(prometheus.CounterOpts{
                Name: "go_app_requests_count",
                Help: "Total App HTTP Requests count.",
        })

func main() {
        // Start the application
        startMyApp()
}

func startMyApp() {
        router := mux.NewRouter()
        router.HandleFunc("/birthday/{name}", func(rw http.ResponseWriter, r *http.Request) {
                        vars := mux.Vars(r)
                        name := vars["name"]
                        greetings := fmt.Sprintf("Happy Birthday %s :)", name)
                        rw.Write([]byte(greetings))

                        REQUEST_COUNT.Inc()
        }).Methods("GET")

        log.Println("Starting the application server...")
        router.Path("/metrics").Handler(promhttp.Handler())
        http.ListenAndServe(":8000", router)

Yukarıdaki Go uygulamasında, uygulamanın alınan HTTP isteklerinin sayısını izlemeyi sağlıyoruz. Bu, uygulamanın ne kadar trafiği işlediğini anlamamıza yardımcı olur.

Uygulamada, "go_app_requests_count" adında bir Prometheus Counter metriği oluşturuyoruz ve bu metriği kullanarak, /birthday/{name} yoluna gelen HTTP isteklerinin toplam sayısını izliyoruz.

  1. İlk olarak, Prometheus'un client_golang kütüphanesini kullanarak uyumlu metrikler oluşturmak için gerekli paketleri içe aktarıyoruz:

import (
    ...
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "github.com/prometheus/client_golang/prometheus/promauto"
)
  1. "github.com/prometheus/client_golang/prometheus": Bu paket, Prometheus metriklerini tanımlamak ve işlemek için kullanılan temel yapıları içerir. Counter, Gauge, Histogram ve Summary gibi metrik türlerini tanımlamak için bu paketin sağladığı yapıları kullanırız.

  2. "github.com/prometheus/client_golang/prometheus/promhttp": Bu paket, Prometheus metriklerini sunan HTTP handler'larını sağlar. Bu paket sayesinde, uygulamanızdaki /metrics yolunu tanımlayarak Prometheus'un metrikleri alabilmesi için bir HTTP endpoint oluşturabilirsiniz. Bu paketin en önemli işlevi olan promhttp.Handler() işlevi, metrikleri döndüren bir HTTP handler oluşturur.

  3. "github.com/prometheus/client_golang/prometheus/promauto": Bu paket, metriklerin otomatik olarak kaydedilmesini sağlar. Bu sayede, uygulamanızdaki metriklerinizi tanımladıktan sonra, Prometheus'un bunları otomatik olarak kaydetmesini ve toplamasını sağlar. Bu paketin NewCounter, NewGauge, NewHistogram ve NewSummary gibi işlevleri, metrikleri otomatik olarak kaydeden nesneler oluşturmak için kullanılır.

Bu modüller, Prometheus'un Go uygulamalarında kullanılabilmesi için gerekli temel yapıları ve işlevleri sağlar. İçe aktarılan bu paketler sayesinde, Go uygulamanızda Prometheus metrikleri tanımlayabilir, bu metrikleri bir HTTP endpoint üzerinden sunabilir ve Prometheus tarafından otomatik olarak toplanmalarını sağlayabilirsiniz.

  1. Daha sonra, uygulamanın HTTP isteklerinin sayısını izlemek için bir Prometheus Counter metriği oluşturuyoruz. Counter, artan sayıları temsil eden ve sadece artırılabilen bir metrik türüdür:

var REQUEST_COUNT = promauto.NewCounter(prometheus.CounterOpts{
    Name: "go_app_requests_count",
    Help: "Total App HTTP Requests count.",
})

Burada, "go_app_requests_count" adında bir Counter metriği oluşturuyoruz ve "Total App HTTP Requests count." açıklamasını ekliyoruz.

  1. /birthday/{name} yolundaki HTTP isteklerini işleyen işlevde, her istek için Counter metriğini 1 artırıyoruz:

func(rw http.ResponseWriter, r *http.Request) {
    ...
    REQUEST_COUNT.Inc()
}

REQUEST_COUNT.Inc() işlevi, metriği 1 birim artırmak için kullanılır.

  1. Son olarak, Prometheus'un uygulama metriklerini alabilmesi için /metrics yolunu tanımlıyoruz:

router.Path("/metrics").Handler(promhttp.Handler())

promhttp.Handler() işlevi, Prometheus metriklerini döndüren bir HTTP handler oluşturur. Bu sayede Prometheus, uygulamadan metrikleri alarak izleme ve uyarılar için kullanabilir.

Özetle, yukarıdaki Go uygulaması, Prometheus ile entegre olarak çalışmak üzere tasarlanmıştır. Uygulamanın HTTP istek sayısını izleyen bir Counter metriği oluşturulmuş ve bu metriği Prometheus'a sunmak için /metrics yolunu kullanıyoruz.

  • Yukarıdaki uygulamayı çalışır duruma getirdikten sonra, Go uygulamamızı "Prometheus" a dahil ediyoruz. Aşağıdaki parametreleri prometheus yaml dosyamıza tanımladıktan sonra, prometheus servisimizi restart ediyoruz.

  - job_name: "prom_go_app"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:
      - targets: ["10.90.0.144:8000"]
  • Gördüğünüz gibi go uygulamamız target olarak eklenmiş durumda.

Prometheus dashboard kullanarak, go uygulamamıza gelen toplan request miktarını görüntüleyebiliriz.

.

.

.

Gauge Metrics

package main

import (
        "net/http"
        "fmt"
        "log"
        "time"
        "github.com/gorilla/mux"
        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "github.com/prometheus/client_golang/prometheus/promauto"
)

var
        REQUEST_INPROGRESS = promauto.NewGauge(prometheus.GaugeOpts{
                Name: "go_app_requests_inprogress",
                Help: "Number of application requests in progress",
        })

func main() {
        // Start the application
        startMyApp()
}

func startMyApp() {
        router := mux.NewRouter()
        router.HandleFunc("/birthday/{name}", func(rw http.ResponseWriter, r *http.Request) {
                        REQUEST_INPROGRESS.Inc()
                        vars := mux.Vars(r)
                        name := vars["name"]
                        greetings := fmt.Sprintf("Happy Birthday %s :)", name)
                        time.Sleep(5 * time.Second)
                        rw.Write([]byte(greetings))

                        REQUEST_INPROGRESS.Dec()
        }).Methods("GET")

        log.Println("Starting the application server...")
        router.Path("/metrics").Handler(promhttp.Handler())
        http.ListenAndServe(":8000", router)

Bu uygulamada, şu anda işlem gören HTTP isteklerinin sayısını izlemeyi sağlıyoruz.

  1. İlk olarak, uygulamanın şu anda işlem gören HTTP isteklerinin sayısını izlemek için bir Prometheus Gauge metriği oluşturuyoruz. Gauge, artan ve azalan sayıları temsil eden ve hem artırılabilen hem de azaltılabilen bir metrik türüdür:

var REQUEST_INPROGRESS = promauto.NewGauge(prometheus.GaugeOpts{
    Name: "go_app_requests_inprogress",
    Help: "Number of application requests in progress",
})

Burada, "go_app_requests_inprogress" adında bir Gauge metriği oluşturuyoruz ve "Number of application requests in progress" açıklamasını ekliyoruz.

  1. /birthday/{name} yolundaki HTTP isteklerini işleyen işlevde, her istek için Gauge metriğini 1 artırıyoruz:

func(rw http.ResponseWriter, r *http.Request) {
    REQUEST_INPROGRESS.Inc()
    ...
}

REQUEST_INPROGRESS.Inc() işlevi, metriği 1 birim artırmak için kullanılır.

  1. İstek işlendikten sonra, Gauge metriğini 1 azaltıyoruz:

func(rw http.ResponseWriter, r *http.Request) {
    ...
    REQUEST_INPROGRESS.Dec()
}

REQUEST_INPROGRESS.Dec() işlevi, metriği 1 birim azaltmak için kullanılır.

  1. Son olarak, Prometheus'un uygulama metriklerini alabilmesi için /metrics yolunu tanımlıyoruz:

router.Path("/metrics").Handler(promhttp.Handler())

promhttp.Handler() işlevi, Prometheus metriklerini döndüren bir HTTP handler oluşturur. Bu sayede Prometheus, uygulamadan metrikleri alarak izleme ve uyarılar için kullanabilir.

Özetle, yukarıdaki Go uygulamasında, şu anda işlem gören HTTP isteklerinin sayısını izlemeyi sağlıyoruz. Uygulamada "go_app_requests_inprogress" adında bir Gauge metriği oluşturuyoruz ve bu metriği kullanarak, şu anda işlem gören isteklerin sayısını izliyoruz.

.

.

.

Summary Metrics

package main

import (
        "net/http"
        "fmt"
        "log"
        "time"
        "github.com/gorilla/mux"
        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "github.com/prometheus/client_golang/prometheus/promauto"
)

var
        REQUEST_RESPOND_TIME = promauto.NewSummaryVec(prometheus.SummaryOpts{
                Name: "go_app_response_latency_seconds",
                Help: "Response latency in seconds.",
        }, []string{"path"})


func routeMiddleware(next http.Handler) http.Handler {

        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                start_time := time.Now()
                route := mux.CurrentRoute(r)
                path, _ := route.GetPathTemplate()

                next.ServeHTTP(w, r)
                time_taken := time.Since(start_time)
                REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds())

        })

}

func main() {
        // Start the application
        startMyApp()
}

func startMyApp() {
        router := mux.NewRouter()
        router.HandleFunc("/birthday/{name}", func(rw http.ResponseWriter, r *http.Request) {
                vars := mux.Vars(r)
                name := vars["name"]
                greetings := fmt.Sprintf("Happy Birthday %s :)", name)

                time.Sleep(5 * time.Second)
                rw.Write([]byte(greetings))

        }).Methods("GET")

        router.Use(routeMiddleware)
        log.Println("Starting the application server...")
        router.Path("/metrics").Handler(promhttp.Handler())
        http.ListenAndServe(":8000", router)
}

Bu uygulamada, uygulamanın HTTP isteklerine yanıt verme süresini ölçmeyi sağlıyoruz.

  1. İlk olarak, yanıt verme süresini izlemek için bir Prometheus SummaryVec metriği oluşturuyoruz. Summary, veri örneklerinin sayısı, toplamı ve istatistiksel dağılımını temsil eden bir metrik türüdür:

var REQUEST_RESPOND_TIME = promauto.NewSummaryVec(prometheus.SummaryOpts{
    Name: "go_app_response_latency_seconds",
    Help: "Response latency in seconds.",
}, []string{"path"})

Burada, "go_app_response_latency_seconds" adında bir SummaryVec metriği oluşturuyoruz ve "Response latency in seconds." açıklamasını ekliyoruz. Ayrıca, "path" etiketi ile isteklerin hangi yola yapıldığını belirtiyoruz.

  1. routeMiddleware adında bir middleware işlevi tanımlıyoruz. Bu işlev, bir HTTP isteğinin süresini ölçmeye ve isteğin tamamlanma süresini Summary metriğine kaydetmeye yardımcı olur:

func routeMiddleware(next http.Handler) http.Handler {
    ...
}
  1. Middleware işlevi içinde, isteğin başlangıç zamanını kaydediyoruz ve isteğin yolunu alıyoruz:

start_time := time.Now()
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
  1. İstek işlendikten sonra, geçen süreyi hesaplayarak Summary metriğine kaydediyoruz:

next.ServeHTTP(w, r)
time_taken := time.Since(start_time)
REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds())

REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds()) işlevi, isteğin tamamlanma süresini ölçen metriği kaydetmek için kullanılır.

  1. Son olarak, Prometheus'un uygulama metriklerini alabilmesi için /metrics yolunu tanımlıyoruz:

router.Path("/metrics").Handler(promhttp.Handler())

promhttp.Handler() işlevi, Prometheus metriklerini döndüren bir HTTP handler oluşturur. Bu sayede Prometheus, uygulamadan metrikleri alarak izleme ve uyarılar için kullanabilir.

Özetle, yukarıdaki Go uygulamasında, uygulamanın HTTP isteklerine yanıt verme süresini ölçmeyi sağlıyoruz. Uygulamada "go_app_response_latency_seconds" adında bir SummaryVec metriği oluşturuyoruz ve bu metriği kullanarak, yanıt verme sürelerini izliyoruz.

REQUEST_RESPOND_TIME metriğine veri kaydetme işlemi, startMyApp() fonksiyonu içerisinde değil, routeMiddleware adlı middleware işlevi içerisinde gerçekleştirilir. routeMiddleware işlevi, HTTP isteklerinin sürelerini ölçen ve bu süreleri REQUEST_RESPOND_TIME metriğine kaydeden bir işleve sahiptir.

startMyApp() fonksiyonu içinde şu kod satırı ile middleware'i kullanıma alıyoruz:

router.Use(routeMiddleware)

router.Use(routeMiddleware) ile routeMiddleware işlevini uygulamanın tüm yollarına uygularız. Bu sayede her bir istek, routeMiddleware işlevi içindeki kodla işlenir ve isteğin süresi REQUEST_RESPOND_TIME metriğine kaydedilir.

routeMiddleware işlevi içinde, isteğin başlangıç zamanını alır, isteğin gerçekleştiği yolun şablonunu alır, ardından isteğin işlenmesini sürdürür ve isteğin tamamlanma süresini ölçer:

start_time := time.Now()
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()

next.ServeHTTP(w, r)
time_taken := time.Since(start_time)

Son olarak, geçen süreyi hesapladıktan sonra, REQUEST_RESPOND_TIME metriğine kaydediyoruz:

REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds())

Bu şekilde, REQUEST_RESPOND_TIME metriği, uygulamanın HTTP isteklerine yanıt verme süresini ölçer ve Prometheus bu metrikler üzerinden uygulamanın performansını takip edebilir.

.

.

.

Histogram Metrics

package main

import (
        "net/http"
        "fmt"
        "log"
        "time"
        "github.com/gorilla/mux"
        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "github.com/prometheus/client_golang/prometheus/promauto"
)

var
        REQUEST_RESPOND_TIME = promauto.NewHistogramVec(prometheus.HistogramOpts{
                Name: "go_app_response_latency_seconds",
                Help: "Response latency in seconds.",
        }, []string{"path"})


func routeMiddleware(next http.Handler) http.Handler {

        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                start_time := time.Now()
                route := mux.CurrentRoute(r)
                path, _ := route.GetPathTemplate()

                next.ServeHTTP(w, r)
                time_taken := time.Since(start_time)
                REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds())

        })

}

func main() {
        // Start the application
        startMyApp()
}

func startMyApp() {
        router := mux.NewRouter()
        router.HandleFunc("/birthday/{name}", func(rw http.ResponseWriter, r *http.Request) {
                vars := mux.Vars(r)
                name := vars["name"]
                greetings := fmt.Sprintf("Happy Birthday %s :)", name)

                time.Sleep(2 * time.Second)
                rw.Write([]byte(greetings))

        }).Methods("GET")

        router.Use(routeMiddleware)
        log.Println("Starting the application server...")
        router.Path("/metrics").Handler(promhttp.Handler())
        http.ListenAndServe(":8000", router)
}

Yukarıdaki Go uygulaması Prometheus için metrikler toplar ve histogram metriği kullanır. Histogram, istek sürelerinin dağılımını temsil eder ve belirli bir süre içinde ne kadar süre harcandığını gösterir. Şimdi Prometheus ile ilgili kısımları açıklayalım.

  1. Histogram metriği tanımlama:

var REQUEST_RESPOND_TIME = promauto.NewHistogramVec(prometheus.HistogramOpts{
        Name: "go_app_response_latency_seconds",
        Help: "Response latency in seconds.",
}, []string{"path"})

Bu kod parçası, go_app_response_latency_seconds adlı bir histogram metriği oluşturur. Bu metrik, yanıt gecikme sürelerini saniye cinsinden gösterir ve etiket olarak "path" kullanır.

  1. Middleware işlevi:

func routeMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start_time := time.Now()
        route := mux.CurrentRoute(r)
        path, _ := route.GetPathTemplate()

        next.ServeHTTP(w, r)
        time_taken := time.Since(start_time)
        REQUEST_RESPOND_TIME.WithLabelValues(path).Observe(time_taken.Seconds())
    })
}

routeMiddleware işlevi, her HTTP isteğinin başlangıç ve bitiş zamanını ölçer ve bu süreyi REQUEST_RESPOND_TIME histogram metriğine kaydeder. İşlev ayrıca, hangi yolun süreyi aldığını belirtmek için "path" etiketini kullanır.

  1. Middleware'i kullanma:

router.Use(routeMiddleware)

Bu kod parçası, routeMiddleware işlevini uygulamamız için kullanılabilir hale getirir. Böylece, her bir istek için yanıt süreleri ölçülür ve metriğe kaydedilir.

  1. Prometheus metriklerini sunma:

router.Path("/metrics").Handler(promhttp.Handler())

Bu satır, uygulamanın /metrics yolunda Prometheus metriklerini sunar. Bu sayede, Prometheus bu yolu tarayarak uygulamanın performans metriklerini toplayabilir.

...

...

...

PreviousExamining the data of our Python applicationNextRecording Rules

Last updated 2 years ago

Was this helpful?

👨‍⚕️
🐐
1 adet işlenen istek mevcut.
Yukarıdaki Prometheus sorgusu, uygulamanın ortalama yanıt süresini hesaplamak için kullanılır. İki rate fonksiyonunun bölümü şeklinde yapılan bu sorgu, belirli bir zaman aralığındaki ortalama yanıt süresini elde etmenizi sağlar. Bu örnekte, 5 dakikalık (5m) bir zaman aralığı kullanılmaktadır. Bu sorgu sayesinde, uygulamanın belirli bir zaman dilimindeki ortalama yanıt süresini (saniye .cinsinden) elde edebilirsiniz.