From fc5c334ad582b76b76f33582021782992b0392c3 Mon Sep 17 00:00:00 2001 From: Frank Brehm Date: Sun, 12 Dec 2010 11:24:15 +0000 Subject: [PATCH] =?utf8?q?Basis=20Objektmodul=20f=C3=BCr=20Logging=20usw.?= =?utf8?q?=20integriert?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit git-svn-id: http://svn.brehm-online.com/svn/my-stuff/nagios/trunk@148 ec8d2aa5-1599-4edb-8739-2b3a1bc399aa --- bin/fbrehm/common/getopt.py | 28 +++++----- bin/fbrehm/common/logging_obj.py | 93 ++++++++++++++++++++++++++++++++ bin/nagios/cfg/struct.py | 40 +++++++------- bin/nagios/config.py | 48 +++++++---------- bin/nagios/object/verify.py | 34 +++++------- 5 files changed, 161 insertions(+), 82 deletions(-) create mode 100755 bin/fbrehm/common/logging_obj.py diff --git a/bin/fbrehm/common/getopt.py b/bin/fbrehm/common/getopt.py index 52b846e..9671e4a 100755 --- a/bin/fbrehm/common/getopt.py +++ b/bin/fbrehm/common/getopt.py @@ -5,13 +5,13 @@ @contact: frank@brehm-online.com @copyright: (c) 2010-2011 by Frank Brehm, Berlin @license: GPL3 -@version: 0.0.1 +@version: 0.0.2 @summary: This module handle all getopt stuff ''' __author__ = 'Frank Brehm ' __copyright__ = '(C) 2010 by Frank Brehm, Berlin' -__version__ = '0.0.1' +__version__ = '0.0.2' import os import sys @@ -35,7 +35,8 @@ class BaseOptParser(object): def __init__( self, prog = '%prog', version = None, description = '', - usage = 'Usage: %s [options]' + usage = 'Usage: %s [options]', + test_option = False ): ''' Costructor. @@ -47,6 +48,8 @@ class BaseOptParser(object): @type description: str @param usage: An usage string fro the help screen, must have a '%s' for the program name @type usage: str + @param test_option: should a test/simulate option be created? - default False + @type test_option: boolean @return: None ''' self.prog = prog @@ -67,15 +70,16 @@ class BaseOptParser(object): usage = self.usage ) - self.addOption( - '--simulate', - '--test', - '-T', - default = False, - action = 'store_true', - dest = 'test', - help = 'set this do simulate commands' - ) + if test_option: + self.addOption( + '--simulate', + '--test', + '-T', + default = False, + action = 'store_true', + dest = 'test', + help = 'set this do simulate commands' + ) self.addOption( '--verbose', diff --git a/bin/fbrehm/common/logging_obj.py b/bin/fbrehm/common/logging_obj.py new file mode 100755 index 0000000..b906453 --- /dev/null +++ b/bin/fbrehm/common/logging_obj.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +@author: Frank Brehm +@contact: frank@brehm-online.com +@copyright: (c) 2010-2011 by Frank Brehm, Berlin +@license: GPL3 +@version: 0.0.1 +@summary: This module includes the base logging object +''' + +__author__ = 'Frank Brehm ' +__copyright__ = '(C) 2010 by Frank Brehm, Berlin' +__contact__ = 'frank@brehm-online.com' +__version__ = '0.0.1' +__license__ = 'GPL3' + +import logging + +class LoggingObject(object): + """Base object with a verbose level and a logging facility. + """ + + #------------------------------------------------------ + def __init__( self, verbose = 0, logger = None ): + """Constructor. + @param verbose: verbosity level (default: 0) + @type verbose: int + @param logger: a logger object for debugging a.s.o., will be created, if None + @type logger: a logging.getLogger object or None + @return: None + @rtype: None + """ + + if not isinstance( verbose, int ): + raise Exception( "verbose is not an integer object" ) + + self.verbose = verbose + + # Logging-Setup + if logger is None: + self.init_logger() + else: + self.logger = logger + + if not ( isinstance( self.logger, logging.Logger ) or isinstance( self.logger, logging.LoggerAdapter ) ) : + raise "self.logger is not a Logger or LoggerAdapter object" + + #------------------------------------------------------ + def init_logger( self, logger_name = 'base_logger' ): + """Initialize the logger property object, maybe overwritten. + In result the object must have a property 'logger' from type 'logging object' + @param logger_name: The name of the logging object + @type logger_name: str + @return: None + @rtype: None + """ + + self.__init_logger( logger_name ) + + #------------------------------------------------------ + def __init_logger( self, logger_name = 'base_logger' ): + """Initialize the logger property object, may NOT overwritten. + In result the object hast a property 'logger' from type 'logging object' + @param logger_name: The name of the logging object + @type logger_name: str + @return: None + @rtype: None + """ + + # Logging-Setup + loglevel = logging.WARNING + logformat = '%(levelname)s: %(message)s' + if self.verbose == 1: + loglevel = logging.INFO + elif self.verbose > 1: + loglevel = logging.DEBUG + logformat = '%(class_name)s - %(module)s.%(funcName)s(%(lineno)d) - %(levelname)s: %(message)s' + + base_logger = logging.getLogger(logger_name) + base_logger.setLevel(loglevel) + + ch = logging.StreamHandler() + ch.setLevel(loglevel) + + formatter = logging.Formatter(logformat) + ch.setFormatter(formatter) + + base_logger.addHandler(ch) + + self.logger = logging.LoggerAdapter( base_logger, { 'class_name': self.__class__.__name__ } ) + +# vim: fileencoding=utf-8 filetype=python ts=4 expandtab diff --git a/bin/nagios/cfg/struct.py b/bin/nagios/cfg/struct.py index f7af332..94310b3 100755 --- a/bin/nagios/cfg/struct.py +++ b/bin/nagios/cfg/struct.py @@ -9,13 +9,14 @@ import re import pprint from datetime import date +from fbrehm.common.logging_obj import LoggingObject from nagios.object.verify import NagiosVerifyError, NagiosObjectVerifier class NagiosConfigStructError(Exception): """Base class for exceptions in this module.""" pass -class NagiosConfigStruct(object): +class NagiosConfigStruct(LoggingObject): """Capsulating class for handling with nagios object structures.""" #------------------------------------------------------ @@ -27,25 +28,21 @@ class NagiosConfigStruct(object): return repr(dump) #------------------------------------------------------ - def __init__( self, logger = None, ignore_empty_object_props = True ): - "Constructor." - - # Logging-Setup - if logger is None: - - self.logger = logging.getLogger('nagiosConfig') - self.logger.setLevel(logging.DEBUG) - - ch = logging.StreamHandler() - ch.setLevel(logging.DEBUG) - - formatter = logging.Formatter("%(name)s - %(funcName)s(%(lineno)d) - %(levelname)s - %(message)s") - ch.setFormatter(formatter) - - self.logger.addHandler(ch) - - else: - self.logger = logger + def __init__( self, logger = None, + ignore_empty_object_props = True, + verbose = 0 ): + """Constructor. + @param logger: a logger object for debugging a.s.o., will be created, if None + @type logger: a logging.getLogger object or None + @param ignore_empty_object_props: Ignore empty property entries in Nagios configuration files (thy will be set to None) - default True + @type ignore_empty_object_props: boolean + @param verbose: verbosity level (default: 0) + @type verbose: int + @return: None + @rtype: None + """ + + super( NagiosConfigStruct, self ).__init__( verbose = verbose, logger = logger ) self.ignore_empty_object_props = ignore_empty_object_props @@ -53,7 +50,8 @@ class NagiosConfigStruct(object): def __del__( self ): "Destructor" - self.logger.debug( "Mayday - someone destroys me!!" ) + if not getattr( self, 'logger', None ) is None: + self.logger.debug( "Mayday - someone destroys me!!" ) #------------------------------------------------------ def get_valid_object_types( self ): diff --git a/bin/nagios/config.py b/bin/nagios/config.py index 0672800..effdb63 100644 --- a/bin/nagios/config.py +++ b/bin/nagios/config.py @@ -20,18 +20,20 @@ import warnings import logging import pprint +from fbrehm.common.logging_obj import LoggingObject from nagios.cfg.struct import NagiosConfigStruct, NagiosConfigStructError -__author__ = 'Frank Brehm' -__contact__ = 'frank@brehm-online.com' -__version__ = '0.1.0' -__license__ = 'GPL3' +__author__ = 'Frank Brehm' +__copyright__ = '(C) 2010 by Frank Brehm, Berlin' +__contact__ = 'frank@brehm-online.com' +__version__ = '0.1.0' +__license__ = 'GPL3' class NagiosConfigError(Exception): """Base class for exceptions in this module.""" pass -class NagiosConfig(object): +class NagiosConfig(LoggingObject): """Klasse zur Kapselung aller Dinge der Nagios-Konfiguration.""" # Konfigurationsverzeichnis von Nagios @@ -78,29 +80,9 @@ class NagiosConfig(object): @type verbose: int @return: None @rtype: None - """ - self.verbose = verbose - loglevel = logging.WARNING - logformat = '%(levelname)s: %(message)s' - if verbose == 1: - loglevel = logging.INFO - elif verbose > 1: - loglevel = logging.DEBUG - logformat = '%(name)s - %(module)s.%(funcName)s(%(lineno)d) - %(levelname)s: %(message)s' - - # Logging-Setup - self.logger = logging.getLogger('nagiosConfig') - self.logger.setLevel(loglevel) - - ch = logging.StreamHandler() - ch.setLevel(loglevel) - - formatter = logging.Formatter(logformat) - ch.setFormatter(formatter) - - self.logger.addHandler(ch) + super( NagiosConfig, self ).__init__( verbose = verbose ) # Other properties @@ -263,13 +245,16 @@ class NagiosConfig(object): #------------------------------------------------------ def read_objects( self ): - "Liest die in der Konfiguration engegebenen Objekt-Kofigurations-Dateien ein" + """Reads the object configuration files from main configuration into self.objects + @return: None + @rtype: None + """ self.objects = {} self.objects_read = {} files = set([]) dirs = set([]) - self.struct_verifier = NagiosConfigStruct( logger = self.logger ) + self.struct_verifier = NagiosConfigStruct( logger = self.base_logger, verbose = self.verbose ) # cfg_file auswerten if 'cfg_file' in self.conf: @@ -316,7 +301,12 @@ class NagiosConfig(object): #------------------------------------------------------ def read_objectfile( self, file_name ): - "Liest eine Datei mit Objektdefinitionen ein und legt diese unter self.objects ab." + """Reads a particular object definition file and saves the structures in self.read_objects. + @param file_name: the filename of the file to read + @type file_name: str + @return: None + @rtype: None + """ self.logger.info( "Reading configuration file {0!r} ...".format( file_name ) ) diff --git a/bin/nagios/object/verify.py b/bin/nagios/object/verify.py index fc6846d..e054eab 100644 --- a/bin/nagios/object/verify.py +++ b/bin/nagios/object/verify.py @@ -8,34 +8,28 @@ import re import logging import pprint +from fbrehm.common.logging_obj import LoggingObject + #----------------------------------------------------------------------- class NagiosVerifyError(Exception): """Base class for exceptions in this module.""" pass #----------------------------------------------------------------------- -class NagiosObjectVerifier(object): +class NagiosObjectVerifier(LoggingObject): #------------------------------------------------------ - def __init__( self, logger = None ): - "Constructor." - - # Logging-Setup - if logger is None: - - self.logger = logging.getLogger('nagiosConfig') - self.logger.setLevel(logging.DEBUG) - - ch = logging.StreamHandler() - ch.setLevel(logging.DEBUG) - - formatter = logging.Formatter("%(name)s - %(funcName)s(%(lineno)d) - %(levelname)s - %(message)s") - ch.setFormatter(formatter) - - self.logger.addHandler(ch) - - else: - self.logger = logger + def __init__( self, logger = None, verbose = 0 ): + """Constructor. + @param logger: a logger object for debugging a.s.o., will be created, if None + @type logger: a logging.getLogger object or None + @param verbose: verbosity level (default: 0) + @type verbose: int + @return: None + @rtype: None + """ + + super( NagiosObjectVerifier, self ).__init__( verbose = verbose, logger = logger ) #------------------------------------------------------ def verify_property( self, definition, type, args = None ): -- 2.39.5