Skip to content

Commit

Permalink
Merge pull request #134 from MUTHU-RAKESH-27/main
Browse files Browse the repository at this point in the history
Restructured the log messages, solved the bug which prints line no and function name of log function
  • Loading branch information
madhansansel authored Feb 3, 2024
2 parents a8306c3 + db18f4f commit b8c9176
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 23 deletions.
5 changes: 4 additions & 1 deletion playbooks/credentials.template
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@ dnac_username: <username>
dnac_password: <password>
dnac_version: 2.3.5.3
dnac_verify: False
dnac_debug: False
dnac_debug: False
dnac_log_level: [CRITICAL, ERROR, WARNING, INFO, DEBUG]
dnac_log_file_path: <file_path>
dnac_log_append: True
4 changes: 4 additions & 0 deletions playbooks/network_settings_intent.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
dnac_verify: "{{ dnac_verify }}"
dnac_debug: "{{ dnac_debug }}"
dnac_log: True
dnac_log_level: "{{ dnac_log_level }}"
dnac_log_append: True
dnac_log_file_path: "{{ dnac_log_file_path }}"
state: merged
config_verify: True
config:
Expand Down Expand Up @@ -95,6 +98,7 @@
dnac_verify: "{{ dnac_verify }}"
dnac_debug: "{{ dnac_debug }}"
dnac_log: True
dnac_log_level: "{{ dnac_log_level }}"
state: deleted
config_verify: True
config:
Expand Down
42 changes: 22 additions & 20 deletions plugins/module_utils/dnac.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,20 @@ def __init__(self, module):

if self.dnac_log and not DnacBase.__is_log_init:
self.dnac_log_level = dnac_params.get("dnac_log_level") or 'WARNING'
self.validate_dnac_log_level()
self.dnac_log_level = self.dnac_log_level.upper()
self.validate_dnac_log_level()
self.dnac_log_file_path = dnac_params.get("dnac_log_file_path") or 'dnac.log'
self.validate_dnac_log_file_path()
self.dnac_log_mode = 'w' if not dnac_params.get("dnac_log_append") else 'a'
self.setup_logger('dnac_file_logger')
self.dnac_file_logger = logging.getLogger('dnac_file_logger')
self.setup_logger('logger')
self.logger = logging.getLogger('logger')
DnacBase.__is_log_init = True
self.dnac_file_logger.debug('Logging configured and initiated')
self.log('Logging configured and initiated', "DEBUG")
elif not self.dnac_log:
# If dnac_log is False, return an empty logger
self.dnac_file_logger = logging.getLogger('empty_logger')
self.logger = logging.getLogger('empty_logger')

self.dnac_file_logger.debug('Dnac parameters: %s', str(dnac_params))
self.log('Dnac parameters: {0}'.format(dnac_params), "DEBUG")
self.supported_states = ["merged", "deleted", "replaced", "overridden", "gathered", "rendered", "parsed"]
self.result = {"changed": False, "diff": [], "response": [], "warnings": []}

Expand Down Expand Up @@ -174,7 +174,8 @@ def setup_logger(self, logger_name):
level = level_mapping.get(self.dnac_log_level, logging.WARNING)

logger = logging.getLogger(logger_name)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s: %(funcName)s: %(lineno)d --- %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(module)s: %(funcName)s: %(lineno)d --- %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S')

file_handler = logging.FileHandler(self.dnac_log_file_path, mode=self.dnac_log_mode)
file_handler.setFormatter(formatter)
Expand Down Expand Up @@ -210,19 +211,21 @@ def log(self, message, level="WARNING", frameIncrement=0):
"""

if self.dnac_log:
message = "Module: " + self.__class__.__name__ + ", " + message
callerframerecord = inspect.stack()[frameIncrement]
# of.write("---- %s ---- %s@%s ---- %s \n" % (d, info.lineno, info.function, msg))
# message = "Module: " + self.__class__.__name__ + ", " + message
class_name = self.__class__.__name__
callerframerecord = inspect.stack()[1 + frameIncrement]
frame = callerframerecord[0]
info = inspect.getframeinfo(frame)
# log_message = "{0}@{1} --- {2}".format(info.lineno, info.function, message)
log_method = getattr(self.dnac_file_logger, level.lower())
log_method(message)
log_message = " %s: %s: %s: %s \n" % (class_name, info.function, info.lineno, message)
log_method = getattr(self.logger, level.lower())
log_method(log_message)

def check_return_status(self):
"""API to check the return status value and exit/fail the module"""

# self.log("status: {0}, msg:{1}".format(self.status, self.msg), frameIncrement=1)
self.dnac_file_logger.debug("status: %s, msg: %s", self.status, self.msg)
self.log("status: {0}, msg: {1}".format(self.status, self.msg), "DEBUG")
if "failed" in self.status:
self.module.fail_json(msg=self.msg, response=[])
elif "exited" in self.status:
Expand Down Expand Up @@ -288,7 +291,7 @@ def get_task_details(self, task_id):
)

self.log('Task Details: {0}'.format(str(response)), 'DEBUG')
self.dnac_file_logger.debug("Retrieving task details by the API 'get_task_by_id' using task ID: %s, Response: %s", str(task_id), str(response))
self.log("Retrieving task details by the API 'get_task_by_id' using task ID: {0}, Response: {1}".format(task_id, response), "DEBUG")

if response and isinstance(response, dict):
result = response.get('response')
Expand Down Expand Up @@ -327,7 +330,7 @@ def check_task_response_status(self, response, validation_string, data=False):
task_id = response.get("taskId")
while True:
task_details = self.get_task_details(task_id)
self.dnac_file_logger.debug('Getting task details from task ID %s: %s', task_id, str(task_details))
self.log('Getting task details from task ID {0}: {1}'.format(task_id, task_details), "DEBUG")

if task_details.get("isError") is True:
if task_details.get("failureReason"):
Expand All @@ -344,7 +347,7 @@ def check_task_response_status(self, response, validation_string, data=False):
self.status = "success"
break

self.dnac_file_logger.debug("progress set to %s for taskid: %s", task_details.get('progress'), task_id)
self.log("progress set to {0} for taskid: {1}".format(task_details.get('progress'), task_id), "DEBUG")

return self

Expand All @@ -365,13 +368,13 @@ def get_execution_details(self, execid):
response (dict) - Status for API execution
"""

self.dnac_file_logger.debug("Execution Id %s", str(execid))
self.log("Execution Id: {0}".format(execid), "DEBUG")
response = self.dnac._exec(
family="task",
function='get_business_api_execution_details',
params={"execution_id": execid}
)
self.dnac_file_logger.debug("Response for the current execution %s", str(response))
self.log("Response for the current execution: {0}".format(response))
return response

def check_execution_response_status(self, response):
Expand All @@ -385,7 +388,6 @@ def check_execution_response_status(self, response):
self
"""

self.dnac_file_logger.debug(str(response))
if not response:
self.msg = "response is empty"
self.status = "failed"
Expand Down Expand Up @@ -447,7 +449,7 @@ def camel_to_snake_case(self, config):
for key, value in config.items():
new_key = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', key).lower()
if new_key != key:
self.dnac_file_logger.debug("%s will be deprecated soon. Please use %s.", key, new_key)
self.log("{0} will be deprecated soon. Please use {1}.".format(key, new_key), "DEBUG")
new_value = self.camel_to_snake_case(value)
new_config[new_key] = new_value
elif isinstance(config, list):
Expand Down
27 changes: 25 additions & 2 deletions plugins/modules/network_settings_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,27 @@
author: Muthu Rakesh (@MUTHU-RAKESH-27)
Madhan Sankaranarayanan (@madhansansel)
options:
dnac_log_file_path:
description:
- Governs logging. Logs are recorded if dnac_log is True.
- If unspecified,
- When 'dnac_log_append' is True, 'dnac.log' is generated in the
current Ansible directory; logs are appended.
- When 'dnac_log_append' is False, 'dnac.log' is generated; logs
are overwritten.
- If a path is specified,
- When 'dnac_log_append' is True, the file opens in append mode.
- When 'dnac_log_append' is False, the file opens in write (w) mode.
- In shared file scenarios, without append mode, content is
overwritten after each module execution.
- For a shared log file, set append to False for the 1st module
(to overwrite); for subsequent modules, set append to True.
type: str
default: dnac.log
dnac_log_append:
description: Determines the mode of the file. Set to True for 'append' mode. Set to False for 'write' mode.
type: bool
default: True
config_verify:
description: Set to True to verify the Cisco DNA Center after applying the playbook config.
type: bool
Expand Down Expand Up @@ -415,7 +436,7 @@
)


class DnacNetwork(DnacBase):
class NetworkSettings(DnacBase):
"""Class containing member attributes for network intent module"""

def __init__(self, module):
Expand Down Expand Up @@ -2125,6 +2146,8 @@ def main():
"dnac_debug": {"type": 'bool', "default": False},
"dnac_log": {"type": 'bool', "default": False},
"dnac_log_level": {"type": 'str', "default": 'WARNING'},
"dnac_log_file_path": {"type": 'str', "default": 'dnac.log'},
"dnac_log_append": {"type": 'bool', "default": True},
"config_verify": {"type": 'bool', "default": False},
"config": {"type": 'list', "required": True, "elements": 'dict'},
"state": {"default": 'merged', "choices": ['merged', 'deleted']},
Expand All @@ -2133,7 +2156,7 @@ def main():

# Create an AnsibleModule object with argument specifications
module = AnsibleModule(argument_spec=element_spec, supports_check_mode=False)
dnac_network = DnacNetwork(module)
dnac_network = NetworkSettings(module)
state = dnac_network.params.get("state")
config_verify = dnac_network.params.get("config_verify")
if state not in dnac_network.supported_states:
Expand Down

0 comments on commit b8c9176

Please sign in to comment.