Last active
January 19, 2024 01:04
-
-
Save alekseyfilippov/952666ffb6b86bab9905f21fe3314fa0 to your computer and use it in GitHub Desktop.
Ansible callback plugin dynamic log path (depends on inventory)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import logging | |
import datetime | |
from ansible.plugins.callback import CallbackBase | |
from ansible.utils.display import FilterUserInjector | |
from ansible import context | |
class CallbackModule(CallbackBase): | |
CALLBACK_VERSION = 2.0 | |
CALLBACK_TYPE = 'notification' | |
CALLBACK_NAME = 'custom_log_path' | |
def __init__(self): | |
super(CallbackModule, self).__init__() | |
self.logger = logging.getLogger('ansible') | |
def set_log_path(self, inventory_path): | |
if inventory_path is None: | |
self._display.error("Inventory path is absent") | |
return | |
else: | |
log_dir = os.path.join(inventory_path, 'ansible_logs') | |
if not os.path.exists(log_dir): | |
os.makedirs(log_dir) | |
current_date = datetime.datetime.now().strftime("%Y-%m-%d") | |
log_file = os.path.join(log_dir, f'ansible_{current_date}.log') | |
if not os.access(log_dir, os.W_OK): | |
print(f"[WARNING]: Log directory {log_dir} is not writeable, aborting log initialization", | |
file=sys.stderr) | |
return | |
for handler in logging.root.handlers[:]: | |
logging.root.removeHandler(handler) | |
for handler in self.logger.handlers[:]: | |
self.logger.removeHandler(handler) | |
file_handler = logging.handlers.TimedRotatingFileHandler(log_file, when="midnight", interval=1, | |
backupCount=7) | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
file_handler.setFormatter(formatter) | |
file_handler.addFilter(FilterUserInjector()) | |
self.logger.addHandler(file_handler) | |
warning_handler = logging.StreamHandler() | |
warning_handler.setLevel(logging.WARNING) | |
warning_handler.setFormatter(formatter) | |
file_handler.addFilter(FilterUserInjector()) | |
self.logger.addHandler(warning_handler) | |
def v2_playbook_on_start(self, playbook): | |
inventory_path = context.CLIARGS['inventory'][0] | |
self.set_log_path(inventory_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment