🔊 Improved log levels

This commit is contained in:
Wouter de Bruijn 2025-02-26 14:45:20 +01:00
parent b314b2c883
commit 886c5b24b9
No known key found for this signature in database
GPG Key ID: AC71F96733B92BFA
4 changed files with 54 additions and 23 deletions

View File

@ -7,6 +7,7 @@ from copy import deepcopy
from logging import getLogger from logging import getLogger
from os import sys from os import sys
from re import search from re import search
from venv import logger
from zabbix_utils import APIRequestError from zabbix_utils import APIRequestError
@ -19,6 +20,7 @@ from modules.exceptions import (
) )
from modules.hostgroups import Hostgroup from modules.hostgroups import Hostgroup
from modules.interface import ZabbixInterface from modules.interface import ZabbixInterface
from modules.logging import get_logger
from modules.tags import ZabbixTags from modules.tags import ZabbixTags
from modules.tools import field_mapper, remove_duplicates from modules.tools import field_mapper, remove_duplicates
from modules.usermacros import ZabbixUsermacros from modules.usermacros import ZabbixUsermacros
@ -111,7 +113,7 @@ class PhysicalDevice:
self.ip = self.cidr.split("/")[0] self.ip = self.cidr.split("/")[0]
else: else:
e = f"Host {self.name}: no primary IP." e = f"Host {self.name}: no primary IP."
self.logger.info(e) self.logger.warning(e)
raise SyncInventoryError(e) raise SyncInventoryError(e)
# Check if device has custom field for ZBX ID # Check if device has custom field for ZBX ID
@ -193,6 +195,7 @@ class PhysicalDevice:
f"found for {self.nb.device_type.manufacturer.name}" f"found for {self.nb.device_type.manufacturer.name}"
f" - {self.nb.device_type.display}." f" - {self.nb.device_type.display}."
) )
self.logger.warning(e)
raise TemplateError(e) raise TemplateError(e)
def get_templates_context(self): def get_templates_context(self):
@ -548,7 +551,7 @@ class PhysicalDevice:
except APIRequestError as e: except APIRequestError as e:
e = f"Host {self.name}: Couldn't create. Zabbix returned {str(e)}." e = f"Host {self.name}: Couldn't create. Zabbix returned {str(e)}."
self.logger.error(e) self.logger.error(e)
raise SyncExternalError(e) from None raise SyncExternalError(e) from e
# Set NetBox custom field to hostID value. # Set NetBox custom field to hostID value.
self.nb.custom_fields[device_cf] = int(self.zabbix_id) self.nb.custom_fields[device_cf] = int(self.zabbix_id)
self.nb.save() self.nb.save()
@ -556,8 +559,9 @@ class PhysicalDevice:
self.logger.info(msg) self.logger.info(msg)
self.create_journal_entry("success", msg) self.create_journal_entry("success", msg)
else: else:
e = f"Host {self.name}: Unable to add to Zabbix. Host already present." self.logger.error(
self.logger.warning(e) f"Host {self.name}: Unable to add to Zabbix. Host already present."
)
def createZabbixHostgroup(self, hostgroups): def createZabbixHostgroup(self, hostgroups):
""" """

36
modules/logging.py Normal file
View File

@ -0,0 +1,36 @@
import logging
from os import path
logger = logging.getLogger("NetBox-Zabbix-sync")
def get_logger():
"""
Return the logger for Netbox Zabbix Sync
"""
return logger
def setup_logger():
"""
Prepare a logger with stream and file handlers
"""
# Set logging
lgout = logging.StreamHandler()
lgfile = logging.FileHandler(
path.join(path.dirname(path.realpath(__file__)), "sync.log")
)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.WARNING,
handlers=[lgout, lgfile],
)
def set_log_levels(root_level, own_level):
"""
Configure log levels for root and Netbox-Zabbix-sync logger
"""
logging.getLogger().setLevel(root_level)
logger.setLevel(own_level)

View File

@ -76,7 +76,7 @@ class ZabbixTags:
else: else:
tag["tag"] = tag_name tag["tag"] = tag_name
else: else:
self.logger.error(f"Tag {tag_name} is not a valid tag name, skipping.") self.logger.warning(f"Tag {tag_name} is not a valid tag name, skipping.")
return False return False
if self.validate_value(tag_value): if self.validate_value(tag_value):
@ -85,7 +85,7 @@ class ZabbixTags:
else: else:
tag["value"] = tag_value tag["value"] = tag_value
else: else:
self.logger.error( self.logger.warning(
f"Tag {tag_name} has an invalid value: '{tag_value}', skipping." f"Tag {tag_name} has an invalid value: '{tag_value}', skipping."
) )
return False return False

View File

@ -14,6 +14,7 @@ from zabbix_utils import APIRequestError, ProcessingError, ZabbixAPI
from modules.device import PhysicalDevice from modules.device import PhysicalDevice
from modules.exceptions import EnvironmentVarError, HostgroupError, SyncError from modules.exceptions import EnvironmentVarError, HostgroupError, SyncError
from modules.logging import get_logger, set_log_levels, setup_logger
from modules.tools import convert_recordset, proxy_prepper from modules.tools import convert_recordset, proxy_prepper
from modules.virtual_machine import VirtualMachine from modules.virtual_machine import VirtualMachine
@ -40,19 +41,9 @@ except ModuleNotFoundError:
) )
sys.exit(1) sys.exit(1)
# Set logging
lgout = logging.StreamHandler()
lgfile = logging.FileHandler(
path.join(path.dirname(path.realpath(__file__)), "sync.log")
)
logging.basicConfig( setup_logger()
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", logger = get_logger()
level=logging.WARNING,
handlers=[lgout, lgfile],
)
logger = logging.getLogger("NetBox-Zabbix-sync")
def main(arguments): def main(arguments):
@ -60,13 +51,13 @@ def main(arguments):
# pylint: disable=too-many-branches, too-many-statements # pylint: disable=too-many-branches, too-many-statements
# set environment variables # set environment variables
if arguments.verbose: if arguments.verbose:
logger.setLevel(logging.INFO) set_log_levels(logging.WARNING, logging.INFO)
if arguments.debug: if arguments.debug:
logger.setLevel(logging.DEBUG) set_log_levels(logging.WARNING, logging.DEBUG)
if arguments.debug_all: if arguments.debug_all:
logging.getLogger().setLevel(logging.DEBUG) set_log_levels(logging.DEBUG, logging.DEBUG)
if arguments.quiet: if arguments.quiet:
logging.getLogger().setLevel(logging.ERROR) set_log_levels(logging.ERROR, logging.ERROR)
env_vars = ["ZABBIX_HOST", "NETBOX_HOST", "NETBOX_TOKEN"] env_vars = ["ZABBIX_HOST", "NETBOX_HOST", "NETBOX_TOKEN"]
if "ZABBIX_TOKEN" in environ: if "ZABBIX_TOKEN" in environ:
@ -202,7 +193,7 @@ def main(arguments):
# Delete device from Zabbix # Delete device from Zabbix
# and remove hostID from NetBox. # and remove hostID from NetBox.
vm.cleanup() vm.cleanup()
logger.info(f"VM {vm.name}: cleanup complete") logger.debug(f"VM {vm.name}: cleanup complete")
continue continue
# Device has been added to NetBox # Device has been added to NetBox
# but is not in Activate state # but is not in Activate state