Improve debug

- Try to factorise initialize_logger into redfish.config.
- Remove global logger declaration to avoid potential side effects.
- Add new logging.debug instead of print and try to cleanup.
- Allow logger.setlevel to be more flexible by configuring console and
  file level of log.
- Prepare client to allow optional debug parameter with loglevel
  selection.
This commit is contained in:
Uggla 2016-01-02 16:31:41 +01:00
parent feff4fb692
commit 6b4db2baef
4 changed files with 83 additions and 57 deletions

View File

@ -204,34 +204,39 @@ if __name__ == '__main__':
'''Main application redfish-client'''
# Functions
def initialize_logger(redfish_logfile, logger_level):
'''Initialize a global loggeer to track application behaviour
def initialize_logger(redfish_logfile,
console_logger_level,
file_logger_level):
'''Initialize a global logger to track application behaviour
:param redfish_logfile: log file name
:param redfish_logfile: Log filename
:type str
:param logger_level: log level (logging.DEBUG, logging.ERROR, ...)
:param screen_logger_level: Console log level
(logging.DEBUG, logging.ERROR, ..) or nolog
:type logging constant or string
:param file_logger_level: File log level
:type logging constant
:returns: True
'''
global logger
logger = logging.getLogger()
logger = logging.getLogger(__name__)
logger.setLevel(logger_level)
formatter = logging.Formatter(
'%(asctime)s :: %(levelname)s :: %(message)s'
)
file_handler = RotatingFileHandler(redfish_logfile, 'a', 1000000, 1)
# First logger to file
file_handler.setLevel(logger_level)
file_handler.setLevel(file_logger_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Second logger to console
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logger_level)
logger.addHandler(steam_handler)
if console_logger_level != "nolog":
steam_handler = logging.StreamHandler()
steam_handler.setLevel(console_logger_level)
logger.addHandler(steam_handler)
return True
def show_manager(all=False):
@ -269,31 +274,48 @@ if __name__ == '__main__':
print ('Redfish API version : %s \n' % remote_mgmt.get_api_version())
# Main program
redfishclient_version = "redfish-client 0.1"
# Parse and manage arguments
arguments = docopt.docopt(__doc__, version=redfishclient_version)
# Initialize logger
logger = None
initialize_logger('redfish-client.log', logging.DEBUG)
#initialize_logger('redfish-client.log', "nolog", logging.DEBUG)
logger = redfish.config.initialize_logger('redfish-client.log',
"nolog",
logging.DEBUG,
__name__)
redfish.config.TORTILLADEBUG = False
#redfish.config.
logger.info("*** Starting %s ***" % redfishclient_version)
logger.info("Arguments parsed")
logger.debug(arguments)
# Get $HOME environment.
HOME = os.getenv('HOME')
if HOME == '':
if not HOME:
print('$HOME environment variable not set, please check your system')
logger.error('$HOME environment variable not set')
sys.exit(1)
# Parse and manage arguments
arguments = docopt.docopt(__doc__, version='redfish-client 0.1')
logger.debug(arguments)
logger.debug("Home directory : %s" % HOME)
arguments['--conf_file'] = arguments['--conf_file'].replace('~', HOME)
conf_file = ConfigFile(arguments['--conf_file'])
if arguments['config'] is True:
logger.debug("Config commands")
if arguments['show'] is True:
logger.debug('show command')
show_manager()
elif arguments['showall'] is True:
logger.debug('showall command')
show_manager(True)
elif arguments['add'] is True:
logger.debug('add command')
conf_file.add_manager(arguments['<manager_name>'],
arguments['<manager_url>'],
arguments['<login>'],
@ -301,10 +323,12 @@ if __name__ == '__main__':
logger.debug(pprint.pprint(conf_file.data))
conf_file.save()
elif arguments['del'] is True:
logger.debug('del command')
conf_file.delete_manager(arguments['<manager_name>'])
logger.debug(pprint.pprint(conf_file.data))
conf_file.save()
elif arguments['modify'] is True:
logger.debug('modify command')
if arguments['url'] is not False:
conf_file.modify_manager(arguments['<manager_name>'],
'url',
@ -324,7 +348,9 @@ if __name__ == '__main__':
logger.debug(pprint.pprint(conf_file.data))
conf_file.save()
if arguments['manager'] is True:
logger.debug("Manager commands")
if arguments['getinfo'] is True:
logger.debug('getinfo command')
# If manager is not defined set it to 'default'
if not arguments['<manager_name>']:
manager_name = 'default'
@ -337,4 +363,5 @@ if __name__ == '__main__':
else:
get_manager_info(manager_name, True)
logger.info("Client session teminated")
sys.exit(0)

View File

@ -4,34 +4,46 @@ import logging
from logging.handlers import RotatingFileHandler
# Global variable definition
TORTILLADEBUG = True
logger = None
TORTILLADEBUG = True
REDFISH_LOGFILE = "/var/log/python-redfish/python-redfish.log"
CONSOLE_LOGGER_LEVEL = logging.DEBUG
FILE_LOGGER_LEVEL = logging.DEBUG
def initialize_logger(redfish_logfile):
"""Return api version.
def initialize_logger(REDFISH_LOGFILE,
CONSOLE_LOGGER_LEVEL,
FILE_LOGGER_LEVEL,
logger_name=""):
'''Initialize a global logger to track application behaviour
:param redfish_logfile: redfish log
:param redfish_logfile: Log filename
:type str
:returns: True
:param screen_logger_level: Console log level
(logging.DEBUG, logging.ERROR, ..) or nolog
:type logging constant or string
:param file_logger_level: File log level
:type logging constant
:returns: logging object
"""
global logger
logger = logging.getLogger()
'''
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s :: %(levelname)s :: %(message)s'
)
file_handler = RotatingFileHandler(redfish_logfile, 'a', 1000000, 1)
file_handler = RotatingFileHandler(REDFISH_LOGFILE, 'a', 1000000, 1)
# First logger to file
file_handler.setLevel(logging.DEBUG)
file_handler.setLevel(FILE_LOGGER_LEVEL)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Second logger to console
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logging.DEBUG)
logger.addHandler(steam_handler)
return True
if CONSOLE_LOGGER_LEVEL != "nolog":
steam_handler = logging.StreamHandler()
steam_handler.setLevel(CONSOLE_LOGGER_LEVEL)
logger.addHandler(steam_handler)
return logger

View File

@ -117,7 +117,7 @@ Clients should always be prepared for:
# coding=utf-8
import sys
import json
from urlparse import urlparse
import requests
@ -126,21 +126,7 @@ import types
import mapping
import exception
# Global variable definition
redfish_logfile = "/var/log/python-redfish/python-redfish.log"
# ===============================================================================
# TODO : create method to set logging level and TORTILLADEBUG.
# ===============================================================================
def set_log_file(logfile):
global redfish_logfile
redfish_logfile = logfile
return True
""" Function to wrap RedfishConnection """
"""Function to wrap RedfishConnection"""
def connect(
@ -150,9 +136,8 @@ def connect(
simulator=False,
enforceSSL=True,
verify_cert=True
):
global redfish_logfile
config.initialize_logger(redfish_logfile)
):
return RedfishConnection(
url,
user,
@ -173,9 +158,11 @@ class RedfishConnection(object):
simulator=False,
enforceSSL=True,
verify_cert=True
):
):
"""Initialize a connection to a Redfish service."""
super(RedfishConnection, self).__init__()
config.logger = config.initialize_logger(config.REDFISH_LOGFILE,
config.CONSOLE_LOGGER_LEVEL,
config.FILE_LOGGER_LEVEL)
config.logger.info("Initialize python-redfish")

View File

@ -49,7 +49,7 @@ class Base(object):
config.logger.info("Raise a RedfishException to upper level")
msg = "Connection error\n"
raise exception.NonTrustedCertificatException(msg)
print self.data
config.logger.debug(self.data)
def get_link_url(self, link_type):
"""Need to be explained.
@ -113,10 +113,10 @@ class Base(object):
# Craft the request
action = dict()
action[parameter_name] = value
print(action)
config.logger.debug(action)
# Perform the POST action
print self.api_url
config.logger.debug(self.api_url)
response = self.api_url.patch(verify=self.connection_parameters.verify_cert,
headers={'x-auth-token': self.connection_parameters.auth_token},
data=action
@ -144,7 +144,7 @@ class BaseCollection(Base):
self.links.append(urljoin(self.url, getattr(link, mapping.redfish_mapper.map_links_ref())))
print self.links
config.logger.debug(self.links)
class Root(Base):