From d2d7c52cbf7db1ed82823e584a4bcaa6f4849f84 Mon Sep 17 00:00:00 2001 From: Daniel Langbein Date: Wed, 1 Nov 2023 12:54:26 +0100 Subject: [PATCH] journald compatible log levels --- src/de/p1st/monitor/csv_util.py | 4 ++- src/de/p1st/monitor/datetime_util.py | 22 ++++++------ src/de/p1st/monitor/loggers/network.py | 4 +-- src/de/p1st/monitor/main.py | 14 ++++---- src/de/p1st/monitor/print_util.py | 46 ++++++++++++++++++++++++++ src/de/p1st/monitor/warn.py | 14 ++++---- 6 files changed, 77 insertions(+), 27 deletions(-) create mode 100644 src/de/p1st/monitor/print_util.py diff --git a/src/de/p1st/monitor/csv_util.py b/src/de/p1st/monitor/csv_util.py index fa30a2d..058e6dc 100644 --- a/src/de/p1st/monitor/csv_util.py +++ b/src/de/p1st/monitor/csv_util.py @@ -4,6 +4,8 @@ import csv from collections import deque from pathlib import Path +from de.p1st.monitor.print_util import print_debug + def read(file: Path) -> list[list[str]]: """ @@ -84,7 +86,7 @@ def append(file: Path, rows: list[list[str]]) -> None: def test(): file = Path('/var/log/de-p1st-monitor/cpu_avg.csv') data = read_last(file, 4, 10) - print(data) + print_debug(data) if __name__ == '__main__': diff --git a/src/de/p1st/monitor/datetime_util.py b/src/de/p1st/monitor/datetime_util.py index d5b6b98..97a5cae 100755 --- a/src/de/p1st/monitor/datetime_util.py +++ b/src/de/p1st/monitor/datetime_util.py @@ -2,23 +2,25 @@ # -*- coding: utf-8 -*- from datetime import datetime, timezone +from de.p1st.monitor.print_util import print_debug + def test(): dt = datetime.now() - print('non UTC:') - print(dt) + print_debug('non UTC:') + print_debug(dt) - print('\nUTC:') - print(now()) - print(to_str(now())) - print(now_str()) - print(from_str(to_str(now()))) + print_debug('\nUTC:') + print_debug(now()) + print_debug(to_str(now())) + print_debug(now_str()) + print_debug(from_str(to_str(now()))) - print('\nlocalized:') - print(dt.tzinfo) + print_debug('\nlocalized:') + print_debug(dt.tzinfo) dt = dt.replace(tzinfo=timezone.utc) - print(dt) + print_debug(dt) def now() -> datetime: diff --git a/src/de/p1st/monitor/loggers/network.py b/src/de/p1st/monitor/loggers/network.py index 62566f6..b6a16bb 100644 --- a/src/de/p1st/monitor/loggers/network.py +++ b/src/de/p1st/monitor/loggers/network.py @@ -9,6 +9,7 @@ import psutil from de.p1st.monitor import datetime_util, csv_util from de.p1st.monitor.logger import Logger from de.p1st.monitor.logger_ex import LoggerReadEx +from de.p1st.monitor.print_util import print_debug from de.p1st.monitor.warn import WarnLevel, WarnMessage @@ -43,8 +44,7 @@ class NetworkLogger(Logger): delta_received = curr_row[2] - prev_row[2] if delta_sent < 0 or delta_received < 0: - print(f'bytes received/sent counter did overflow after {prev_row[0]}', - file=sys.stderr) + print_debug(f'bytes received/sent counter did overflow after {prev_row[0]}') continue elapsed_seconds = elapsed_time.total_seconds() diff --git a/src/de/p1st/monitor/main.py b/src/de/p1st/monitor/main.py index d4836de..e2e855d 100755 --- a/src/de/p1st/monitor/main.py +++ b/src/de/p1st/monitor/main.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse -import sys from pathlib import Path from de.p1st.monitor.cfg.singleton import init_cfg from de.p1st.monitor.cfg.loggers import get_loggers from de.p1st.monitor.logger_ex import LoggerReadEx +from de.p1st.monitor.print_util import print_err, print_debug def main(): @@ -34,13 +34,13 @@ def main(): def export(): loggers, logger_arg_exs = get_loggers() if len(logger_arg_exs) > 0: - print('\nCONFIGURATION ERROR: Could not instantiate some of the loggers!', file=sys.stderr) + print_err('\nCONFIGURATION ERROR: Could not instantiate some of the loggers!') print_exs(logger_arg_exs, [f'{n}.' for n in range(1, 1 + len(logger_arg_exs))]) exit(1) for logger in loggers: export_path: Path = logger.export_data() - print(export_path) + print_debug(export_path) def log(): @@ -48,7 +48,7 @@ def log(): logger_read_exs = [] logger_warnings = 0 for logger_ct, logger in enumerate(loggers, start=1): - # print(f'Running logger {logger_ct}/{len(loggers)} ...') + # print_debug(f'Running logger {logger_ct}/{len(loggers)} ...') try: logger.update() except LoggerReadEx as e: @@ -59,10 +59,10 @@ def log(): logger_warnings += 1 if len(logger_arg_exs) > 0: - print('\nCONFIGURATION ERROR: Could not instantiate some of the loggers!', file=sys.stderr) + print_err('\nCONFIGURATION ERROR: Could not instantiate some of the loggers!') print_exs(logger_arg_exs, [f'{n}.' for n in range(1, 1 + len(logger_arg_exs))]) if len(logger_read_exs) > 0: - print('\nRUNTIME ERROR: Some loggers could not fetch sensor data!', file=sys.stderr) + print_err('\nRUNTIME ERROR: Some loggers could not fetch sensor data!') print_exs(logger_read_exs, [f'{n}.' for n in range(1, 1 + len(logger_read_exs))]) if len(logger_arg_exs) + len(logger_read_exs) > 0 or logger_warnings > 0: @@ -74,7 +74,7 @@ def print_exs(exs: list[Exception], headers: list): # Indent str(e) with \t body = '\t' + '\n\t'.join(str(e).splitlines()) - print(f'{header}\n{body}', file=sys.stderr) + print_err(f'{header}\n{body}') if __name__ == '__main__': diff --git a/src/de/p1st/monitor/print_util.py b/src/de/p1st/monitor/print_util.py new file mode 100644 index 0000000..4cc6677 --- /dev/null +++ b/src/de/p1st/monitor/print_util.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import sys + + +# https://www.freedesktop.org/software/systemd/man/latest/sd-daemon.html +# +# define SD_EMERG "<0>" /* system is unusable */ +# define SD_ALERT "<1>" /* action must be taken immediately */ +# define SD_CRIT "<2>" /* critical conditions */ +# define SD_ERR "<3>" /* error conditions */ +# define SD_WARNING "<4>" /* warning conditions */ +# define SD_NOTICE "<5>" /* normal but significant condition */ +# define SD_INFO "<6>" /* informational */ +# define SD_DEBUG "<7>" /* debug-level messages */ + +def print_emerg(message: object): + print(f'<0> {message}', file=sys.stderr) + + +def print_alert(message: object): + print(f'<1> {message}', file=sys.stderr) + + +def print_crit(message: object): + print(f'<2> {message}', file=sys.stderr) + + +def print_err(message: object): + print(f'<3> {message}', file=sys.stderr) + + +def print_warning(message: object): + print(f'<4> {message}', file=sys.stderr) + + +def print_notice(message: object): + print(f'<5> {message}', file=sys.stdout) + + +def print_info(message: object): + print(f'<6> {message}', file=sys.stdout) + + +def print_debug(message: object): + print(f'<7> {message}', file=sys.stdout) diff --git a/src/de/p1st/monitor/warn.py b/src/de/p1st/monitor/warn.py index 75a497f..92a25cf 100644 --- a/src/de/p1st/monitor/warn.py +++ b/src/de/p1st/monitor/warn.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import annotations -import sys from datetime import datetime from enum import Enum from functools import total_ordering -from typing import TextIO + +from de.p1st.monitor.print_util import print_warning, print_crit # https://docs.python.org/3/library/functools.html#functools.total_ordering @@ -58,8 +58,12 @@ class WarnMessage: """ if self.level == WarnLevel.NONE: pass + elif self.level == WarnLevel.NORMAL: + print_warning(self.formatted_message()) + elif self.level == WarnLevel.HIGH: + print_crit(self.formatted_message()) else: - print(self.formatted_message(), file=self.file()) + raise NotImplementedError() return self @@ -73,7 +77,3 @@ class WarnMessage: return f'[CRITICAL] {self.date}: ' return f'{self.date}: ' - def file(self) -> TextIO: - if self.level == WarnLevel.NONE: - raise ValueError() - return sys.stderr