Fixing logging issues in the previous modifications

This commit is contained in:
benoit 2023-03-16 13:11:40 +01:00 committed by Benoit
parent 7eea4c94be
commit dff95eae2f
5 changed files with 43 additions and 22 deletions

View file

@ -1 +1,5 @@
import logging
__version__ = "0.1.1" __version__ = "0.1.1"
_log: logging.Logger = logging.getLogger(__name__)

View file

@ -6,7 +6,7 @@ import click
import nagiosplugin import nagiosplugin
from typing import List from typing import List
from . import __version__ from . import __version__, _log
from .cluster import ( from .cluster import (
ClusterConfigHasChanged, ClusterConfigHasChanged,
ClusterConfigHasChangedSummary, ClusterConfigHasChangedSummary,
@ -33,8 +33,11 @@ from .node import (
from .types import ConnectionInfo, Parameters from .types import ConnectionInfo, Parameters
from .convert import size_to_byte from .convert import size_to_byte
_log = logging.getLogger(__name__)
DEFAULT_CFG = "config.ini" DEFAULT_CFG = "config.ini"
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
_log.addHandler(handler)
def print_version(ctx: click.Context, param: str, value: str) -> None: def print_version(ctx: click.Context, param: str, value: str) -> None:
@ -166,8 +169,9 @@ def main(
endpoints = tendpoints endpoints = tendpoints
if verbose == 3: if verbose == 3:
logging.basicConfig(format="%(levelname)s - %(message)s", level=logging.DEBUG) logging.getLogger("urllib3").addHandler(handler)
logging.getLogger("urllib3").setLevel(logging.DEBUG) logging.getLogger("urllib3").setLevel(logging.DEBUG)
_log.setLevel(logging.DEBUG)
connection_info: ConnectionInfo connection_info: ConnectionInfo
if cert_file is None and key_file is None: if cert_file is None and key_file is None:

View file

@ -1,15 +1,13 @@
import hashlib import hashlib
import json import json
import logging
from collections import Counter from collections import Counter
import nagiosplugin import nagiosplugin
from typing import Iterable, Union from typing import Iterable, Union
from . import _log
from .types import PatroniResource, ConnectionInfo, handle_unknown from .types import PatroniResource, ConnectionInfo, handle_unknown
_log = logging.getLogger(__name__)
def replace_chars(text: str) -> str: def replace_chars(text: str) -> str:
return text.replace("'", "").replace(" ", "_") return text.replace("'", "").replace(" ", "_")
@ -134,17 +132,23 @@ class ClusterConfigHasChanged(PatroniResource):
new_hash = hashlib.md5(json.dumps(item_dict).encode()).hexdigest() new_hash = hashlib.md5(json.dumps(item_dict).encode()).hexdigest()
_log.debug(f"save result: {self.save}") _log.debug("save result: %(save)s", {"issave": self.save})
old_hash = self.config_hash old_hash = self.config_hash
if self.state_file is not None and self.save: if self.state_file is not None and self.save:
_log.debug(f"saving new hash to state file / cookie {self.state_file}") _log.debug(
"saving new hash to state file / cookie %(state_file)s",
{"state_file": self.state_file},
)
cookie = nagiosplugin.Cookie(self.state_file) cookie = nagiosplugin.Cookie(self.state_file)
cookie.open() cookie.open()
cookie["hash"] = new_hash cookie["hash"] = new_hash
cookie.commit() cookie.commit()
cookie.close() cookie.close()
_log.debug(f"hash info: old hash {old_hash}, new hash {new_hash}") _log.debug(
"hash info: old hash %(old_hash)s, new hash %(new_hash)s",
{"old_hash": old_hash, "new_hash": new_hash},
)
return [ return [
nagiosplugin.Metric( nagiosplugin.Metric(

View file

@ -1,12 +1,9 @@
import logging
import nagiosplugin import nagiosplugin
from typing import Iterable from typing import Iterable
from . import _log
from .types import APIError, ConnectionInfo, handle_unknown, PatroniResource from .types import APIError, ConnectionInfo, handle_unknown, PatroniResource
_log = logging.getLogger(__name__)
class NodeIsPrimary(PatroniResource): class NodeIsPrimary(PatroniResource):
def probe(self: "NodeIsPrimary") -> Iterable[nagiosplugin.Metric]: def probe(self: "NodeIsPrimary") -> Iterable[nagiosplugin.Metric]:
@ -101,17 +98,23 @@ class NodeTLHasChanged(PatroniResource):
item_dict = self.rest_api("patroni") item_dict = self.rest_api("patroni")
new_tl = item_dict["timeline"] new_tl = item_dict["timeline"]
_log.debug(f"save result: {self.save}") _log.debug("save result: %(issave)s", {"issave": self.save})
old_tl = self.timeline old_tl = self.timeline
if self.state_file is not None and self.save: if self.state_file is not None and self.save:
_log.debug(f"saving new timeline to state file / cookie {self.state_file}") _log.debug(
"saving new timeline to state file / cookie %(state_file)s",
{"state_file": self.state_file},
)
cookie = nagiosplugin.Cookie(self.state_file) cookie = nagiosplugin.Cookie(self.state_file)
cookie.open() cookie.open()
cookie["timeline"] = new_tl cookie["timeline"] = new_tl
cookie.commit() cookie.commit()
cookie.close() cookie.close()
_log.debug(f"Tl data: old tl {old_tl}, new tl {new_tl}") _log.debug(
"Tl data: old tl %(old_tl)s, new tl %(new_tl)s",
{"old_tl": old_tl, "new_tl": new_tl},
)
# The actual check # The actual check
yield nagiosplugin.Metric( yield nagiosplugin.Metric(
@ -149,7 +152,8 @@ class NodePatroniVersion(PatroniResource):
version = item_dict["patroni"]["version"] version = item_dict["patroni"]["version"]
_log.debug( _log.debug(
f"Version data: patroni version {version} input version {self.patroni_version}" "Version data: patroni version %(version)s input version %(patroni_version)s",
{"version": version, "patroni_version": self.patroni_version},
) )
# The actual check # The actual check

View file

@ -1,4 +1,3 @@
import logging
from urllib.parse import urlparse from urllib.parse import urlparse
import attr import attr
@ -6,7 +5,7 @@ import nagiosplugin
import requests import requests
from typing import Any, Callable, List, Optional, Tuple, Union from typing import Any, Callable, List, Optional, Tuple, Union
_log = logging.getLogger(__name__) from . import _log
class APIError(requests.exceptions.RequestException): class APIError(requests.exceptions.RequestException):
@ -46,7 +45,13 @@ class PatroniResource(nagiosplugin.Resource):
verify = self.conn_info.ca_cert verify = self.conn_info.ca_cert
_log.debug( _log.debug(
f"Trying to connect to {endpoint}/{service} with cert: {cert} verify: {verify}" "Trying to connect to %(endpoint)s/%(service)s with cert: %(cert)s verify: %(verify)s",
{
"endpoint": endpoint,
"service": service,
"cert": cert,
"verify": verify,
},
) )
try: try:
@ -54,8 +59,8 @@ class PatroniResource(nagiosplugin.Resource):
except Exception as e: except Exception as e:
_log.debug(e) _log.debug(e)
continue continue
# The status code is already handled by urllib3 # The status code is already displayed by urllib3
_log.debug(f"api call data: {r.text}") _log.debug("api call data: %(data)s", {"data": r.text})
if r.status_code != 200: if r.status_code != 200:
raise APIError( raise APIError(