metrics.cpu_metric

This commit is contained in:
Jörn-Michael Miehe 2023-08-31 09:00:22 +00:00
parent a8ca283467
commit 1854c4d40e
3 changed files with 41 additions and 3 deletions

View file

@ -1,8 +1,7 @@
import os
import shutil
import psutil
from .metrics import cpu_metric
from .settings import SETTINGS
@ -11,7 +10,7 @@ def main() -> None:
print(SETTINGS.model_dump())
# CPU metric
print(psutil.cpu_percent(interval=1))
print(cpu_metric())
# MEM metric

View file

@ -0,0 +1,36 @@
from dataclasses import dataclass, field
import psutil
from .settings import SETTINGS, MetricSettings
@dataclass(slots=True, frozen=True)
class Report:
result: str
failed: bool = field(default=False, kw_only=True)
def _report(
settings: MetricSettings,
name: str,
value: float,
) -> Report | None:
if not settings.enabled:
return None
result = settings.report.format(name=name, value=value)
if (
value > settings.threshold and not settings.inverted
or value < settings.threshold and settings.inverted
):
return Report(result, failed=True)
else:
return Report(result)
def cpu_metric() -> Report | None:
value = psutil.cpu_percent(interval=1)
return _report(SETTINGS.cpu, "CPU", value)

View file

@ -8,6 +8,9 @@ class MetricSettings(BaseModel):
# metric will be reported
enabled: bool = True
# format string to report the metric
report: str = "{name}: {value:.2f}%"
# if the metric value exceeds this percentage, the report fails
threshold: float