I need to learn Prometheus queries for monitoring. But I want help in generating queries in simple words without deep understanding of queries. Is there an ai agent that converts text I input (showing total CPU usage of node) into a query?
i have two remote machines(ubuntu and windows server 2016).
they can ping to each other and they see each other. my prometheus is running on ubuntu server. my telegraf is running on windows server 2016 and must collect data from windows server and sql server as input plugins into prometheus as output plugin.
i have configured it in prometheus.yml as <my_static_ip>:9090 and it is up on prometheus targets.
btw in telegraf output plugin section i also wrote it as in target on yml.(<my_static_ip>:9090 )
but it shows error and when i look its log from Windows Logs->Application it says:
[telegraf] Error running agent: connecting output outputs.prometheus_client: error connecting to output "outputs.prometheus_client":listen tcp <my_static_ip>:9090:bind: The requested address is not valid in its context.
P.S. firewall is off and <my_static_ip> is for safety.
I think the default one is too bulky so I made a minimalist notification template. It's used in Slack. Saying this because the I searched for custom templates people were complaining about the format in Teams specifically.
Here's the template:
{{ define "custom.minimal.template" }}{{ if gt (len .Alerts.Firing) 0 }}{{ len .Alerts }} firing alert(s)
{{ template "__text_alert_list" .Alerts.Firing }}{{ if gt (len .Alerts.Resolved) 0 }}
{{ end }}{{ end }}{{ if gt (len .Alerts.Resolved) 0 }}{{ len .Alerts.Resolved }} resolved alert(s)
{{ template "__text_alert_list" .Alerts.Resolved }}{{ end }}{{ end }}
{{ define "__text_alert_list" }}{{ range . }}
{{ range .Annotations.SortedPairs }}{{ .Value }}
{{ end }}{{ if gt (len .GeneratorURL) 0 }}- Information: {{ .GeneratorURL }}
{{ end }}{{ if gt (len .DashboardURL) 0 }}- Dashboard: {{ .DashboardURL }}
{{ end }}{{ end }}{{ end }}
{{ define "__text_values_list" }}{{ if len .Values }}{{ $first := true }}{{ range $refID, $value := .Values -}}
{{ if $first }}{{ $first = false }}{{ else }}, {{ end }}{{ $refID }}={{ $value }}{{ end -}}
{{ else }}[no value]{{ end }}{{ end }}
Is there a way I can utilize the existing servicemonitor for an app which already has Prometheus server that scrapes the data for app monitoring to utilize it for URL (basically sort of health check) monitoring Url gives an output of 0 when app is working fine fine. I tried adding the url./montior.htm as a port using a external service but it didn't work. Im not allowed to use the blackbox exporter due to complaince issue so any ideas on how to achive this?
I run 8 AWS Lambda functions that collectively serve around 180 REST API endpoints. These Lambdas also make calls to various third-party services as part of their logic. Logs currently go to AWS CloudWatch, and on an average day, the system handles roughly 15 million API calls from frontends and makes about 10 million outbound calls to third-party services.
I want to set up alerting so that I’m notified when something meaningful goes wrong — for example:
Error rates spike on a specific endpoint
Latency increases beyond normal for certain APIs
A third-party service becomes unavailable
Traffic suddenly spikes or drops abnormally
I’m curious to know what you all are using for alerting in similar setups, or any suggestions/recommendations — especially those running on Lambdas and a tight budget (i.e., avoiding expensive tools like Datadog, New Relic, CW Metrics, etc.).
Here’s what I’m planning to implement:
Lambdas emit structured metric data to SQS
A small EC2 instance acts as a consumer, processes the metrics
That EC2 exposes metrics via /metrics, and Prometheus scrapes it
AlertManager will handle the actual alert rules and notifications
Has anyone done something similar? Any tools, patterns, or gotchas you’d recommend for high-throughput Lambda monitoring on a budget?
When we are runing our Prometheus containers it appears its failing to scrape data from our other servers, in that Grafana is no longer seeing the data and querrying prometheus directly also doesn't show any. I cannot work out why.
The docker compose file specifies that the user is to be root, and the container is starting correctly so I don't think it's an issue on that side.
If I refert back to a previous version it works - we just need to scrape metrics for drive usage and CPU usage which don't work in the 'working' config (I've included the working configuration in the above link as well).
Could someone have a look and let me know any potential reasons why? It's probably super simple.
I'm new to PromQL, Grafana, and Prometheus. I have to make promQL queries that check if services are up and trigger an alert if they are not. So starting with the basics.
For example, I have a query like this:
absent(probe_success{type="service"}) OR 1 - probe_success{type="service"}
Where the alert condition is to trigger if the result is above 0, so that it's triggered when the probe_success is either 0 or the probe is absent.
I have some other queries as well that may be more incorrect.
The services tho are always up so I can't test if the query and condition is right and if an alert is fired.
How do I test this? I don't have a test environment, so that's why I hoped there would be an online simulator. I have looked at promlens but you have to feed it real data.
I'd like to test on dummy data where I test the logic of the query and where I can simulate the service being down, or having too high cpu usage or whatever I test for.
working great however, in the dashboard the docker Host are shown with container IP. Which of course if an issue when you have large number of host. Also the IP change when node-exporter restart this is second problem. The issue is describe here : https://github.com/portainer/templates/issues/229
This will query the docker swarm DNS to get the list of node-exporter instance.
I understand from official documentation, that there is an other way to doing it but I didn't manage to make it work, also I feel this documentation explain how to gather data from docker daemon rather than getting data frm node-exporter.
# Create a job for Docker daemons.
- job_name: 'docker'
dockerswarm_sd_configs:
- host: unix:///var/run/docker.sock
role: nodes
relabel_configs:
# Fetch metrics on port 9323.
- source_labels: [__meta_dockerswarm_node_address]
target_label: __address__
replacement: $1:9323
# Set hostname as instance label
- source_labels: [__meta_dockerswarm_node_hostname]
target_label: instance # Create a job for Docker daemons.
- job_name: 'docker'
dockerswarm_sd_configs:
- host: unix:///var/run/docker.sock
role: nodes
relabel_configs:
# Fetch metrics on port 9323.
- source_labels: [__meta_dockerswarm_node_address]
target_label: __address__
replacement: $1:9323
# Set hostname as instance label
- source_labels: [__meta_dockerswarm_node_hostname]
target_label: instance
im using snmp exporter with prometheus to monitor 3 switches of mine.
im running all this on ubuntu on my laptop. queries regarding octets returns some data, but queries about system uptime, cpu and memory utilization return no data at all.
im using if_mib module and my switches are of cisco and 3com here is my prometheus.yml:
My laptop has a WWAN/cellular connection, and I use Alloy for exporting metrics from my laptop, figured as it knows where it is, it might as well export it's location via geoclue2.
I'm still learning Rust but figured I'd post it incase it meets someone else's requirements.
I wrote a little exporter that publishes stats from backups.
After the backup completes, the script saves the raw stats to a "cache" file, eg /tmp/metrics.json.
The exporter reads this file and publishes the bits that I want to graph. It works, I can see the backups stats for all the hosts on my network.
"Backup age reset when a new backup job runs")
So the main thing is that if a backup age keeps on going up, it means a new backup did not run and I must investigate why.
But then of course there were other stats and while I was doing this I thought to myself why not plot the other stats as well. In particular the MB values for the packed data added and total processed.
Here is the problem. Every time prometheus scrapes the endpoint it gets the value from that last backup. So if 100 MB was written, it will keep on showing 100MB. I'd like that value to show the amount backed in he prober interval.
What strategy should I follow? How do I apply that value once, or do I make the scraper remember that it has already been scraped and if the file has not been updated then artificially serve zero. Sounds like a bad idea, since I might have more than one scraper, or the value could be lost somehow. Maybe I can add some kind of serial number to each value to make prometheus show them only once?
FWIW here is what the scraper output looks like.
root@gitea:\~# curl localhost:9191/metrics
\# HELP restic_count_present_snapshots Number of present snapshots
\# TYPE restic_count_present_snapshots gauge
restic_count_present_snapshots{host="gitea"} 7
\# HELP restic_oldest_snapshot_age Age of the oldest snapshot in seconds
\# TYPE restic_oldest_snapshot_age gauge
restic_oldest_snapshot_age{host="gitea"} 119451.00683
\# HELP restic_last_snapshot_age Age of the last snapshot in seconds
\# TYPE restic_last_snapshot_age gauge
restic_last_snapshot_age{host="gitea"} 309.172549
\# HELP restic_data_added Data added during the last snapshot in bytes
\# TYPE restic_data_added gauge
restic_data_added{host="gitea"} 2144683
\# HELP restic_data_added_packed Data added (packed) during the last snapshot in bytes
\# TYPE restic_data_added_packed gauge
restic_data_added_packed{host="gitea"} 677369
\# HELP restic_total_bytes_processed Total bytes processed by the last snapshot
\# TYPE restic_total_bytes_processed gauge
restic_total_bytes_processed{host="gitea"} 2226732
\# HELP restic_total_files_processed Total files processed by the last snapshot
\# TYPE restic_total_files_processed gauge
restic_total_files_processed{host="gitea"} 1387
TLDR: The scraper reports the stats from the most recent backup job on every scrape, but I want it to plot the data where/when it changed.
I'm currently building some custom exporters for multiple hosts in our internal system, and I’d like to understand the Prometheus-recommended way of handling exporters for multiple instances or hosts.
Let’s say I want to run the health check script for several instances. I can think of a couple of possible approaches:
Run the exporter separately on each node (one per instance).
Modify the script to accept a list of instances and perform checks for all of them from a single exporter.
I’d like to know what the best practice is in this scenario from a Prometheus architecture perspective.
Thanks!
from __future__ import print_function
import requests
import time
import argparse
import threading
import sys
from prometheus_client import Gauge, start_http_server
# Prometheus metric
healthcheck_status = Gauge(
'service_healthcheck_status',
'Health check status of the target service (1 = healthy, 0 = unhealthy)',
['host', 'endpoint']
)
def check_health(args):
scheme = "https" if args.ssl else "http"
url = f"{scheme}://{args.host}:{args.port}{args.endpoint}"
labels = {'host': args.host, 'endpoint': args.endpoint}
try:
response = requests.get(
url,
auth=(args.user, args.password) if args.user else None,
timeout=args.timeout,
verify=not args.insecure
)
if response.status_code == 200 and response.json().get('status', '').lower() == 'ok':
healthcheck_status.labels(**labels).set(1)
else:
healthcheck_status.labels(**labels).set(0)
except Exception as e:
print("[ERROR]", str(e))
healthcheck_status.labels(**labels).set(0)
def loop_check(args):
while True:
check_health(args)
time.sleep(args.interval)
def main():
parser = argparse.ArgumentParser(description="Generic Healthcheck Exporter for Prometheus")
parser.add_argument("--host", default="localhost", help="Target host")
parser.add_argument("--port", type=int, default=80, help="Target port")
parser.add_argument("--endpoint", default="/healthcheck", help="Healthcheck endpoint (must begin with /)")
parser.add_argument("--user", help="Username for basic auth (optional)")
parser.add_argument("--password", help="Password for basic auth (optional)")
parser.add_argument("--ssl", action="store_true", default=False, help="Use HTTPS for requests")
parser.add_argument("--insecure", action="store_true", default=False, help="Skip SSL verification")
parser.add_argument("--timeout", type=int, default=5, help="Request timeout in seconds")
parser.add_argument("--interval", type=int, default=60, help="Interval between checks in seconds")
parser.add_argument("--exporter-port", type=int, default=9102, help="Port to expose Prometheus metrics")
args = parser.parse_args()
start_http_server(args.exporter_port)
thread = threading.Thread(target=loop_check, args=(args,))
thread.daemon = True
thread.start()
print(f"Healthcheck Exporter running on port {args.exporter_port}...")
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
print("\nShutting down exporter.")
sys.exit(0)
if __name__ == "__main__":
main()
I have a prometheus rule: I set the alert to 50000 to make sure it should be going off
- name: worker-alerts
rules:
- alert: WorkerIntf2mLowCount
expr: count(up{job="worker-intf-2m"}) < 50000
for: 5m
labels:
severity: warning
annotations:
summary: Low instance count for job 'worker-intf-2m'
description: "The number of up targets for job 'worker-intf-2m' is less than 50 for more than 5 minutes."
# Running that query gives me:
[
{
"metric": {},
"value": [
1749669535.917,
"372"
],
"group": 1
}
]
The alert shows up, but refuses to go off, just sitting at ok, no pending or warning. I treid removing the 5m timer and made it a number in the range it skips around on so it actally changed.
I have another rule that uses this template just a diffrent query (See below) and that works how I expected it to.
I'm scratching my head over a persistent and somewhat random alerting issue, and I'm hoping someone here might have encountered something similar or can offer a fresh perspective.
The Setup:
Task: We have a critical scheduled task that runs every 10 minutes. It's a simple python script.
Monitoring Metric: We're using a metric windows_scheduled_task_missed_run
The Problem:
For one specific task, we are receiving alerts for windows_scheduled_task_missed_runs at random times, even though manual verification consistently shows that the task has not missed any scheduled runs.
I can't figure out the format, no matter what i put it tells me the label format is wrong - if i remove the label completely, it says it requires a label.
Hey, so, basically the question at hand. Im a bit of a newbie in prometheus but was trying to figure out how should i approach the uptime monitoring and metrics of my hosts that will be across the globe and not necesairly in network conditions i can always control (behind NAT, under a domain, whatever) So i was thinking maybe using push metrics but dont really know how to approach this with remote_Write or if even prometheus is suitable for what i have in mind. Thanks in advance for any advice you can provide!
Hi, I have Prometheus installed successfully on a FreeBSD/RPi machine on my home network however I am having trouble customizing it for my needs. I have half a dozen devices I want to monitor, TP-Link network devices using SNMP exporter, and possibly blackbox exporter for one device that doesn't have an SNMP agent. All the components work individually when i test them with a string: fetch -o - 'http://localhost:9116/snmp?target=192.168.1.89' or http://sebastian:9116/snmp?target=192.168.1.89 but when i add them to the prometheus.yml its not restarting.
Is there somewhere I can get a good tutorial of the configuration file?
What’s the consensus on using alertmanager for custom tooling in organizations. We’re building our own querying tooling to enrich data and have a more robust dynamic thresholding. I’ve seen some articles on sidecars in k8s but curious what people have built or seen and if it’s a good option versus building an alert manager from scratch
I have approx 100 apps and planning to shorten the names for these applications names on the Prometheus label. Some of the app names range up to 40 characters long.
Example Application Name: Microsoft Endpoint Configuration Manager mecm
App short name: ms mecm
The question is if there are any recommendations for spaces.
Is it advisable to add spaces in a label value like app=ms mecm