Skip to content
Snippets Groups Projects
Commit dbc6c610 authored by Simone Spinelli's avatar Simone Spinelli
Browse files

Add a custom callback plugin for managing logs

parent a3c0db3f
No related branches found
No related tags found
1 merge request!277Add a custom callback plugin for managing logs
Pipeline #94916 passed
# callback_plugins/filtering_syslog.py
import syslog
import uuid
from datetime import datetime
from ansible.plugins.callback import CallbackBase
from ansible.utils.display import Display
display = Display()
class CallbackModule(CallbackBase):
"""
Logs all task results to syslog with timestamp and run ID.
One line per result. Only prints tasks tagged with 'print_action'.
Always prints and logs playbook summary.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'filtering_syslog'
def __init__(self):
super().__init__()
syslog.openlog(ident="ansible", logoption=syslog.LOG_PID, facility=syslog.LOG_USER)
self.run_id = str(uuid.uuid4())[:8] # Shorten for readability
def _log_to_syslog(self, message: str):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
syslog.syslog(syslog.LOG_INFO, f"[{timestamp}] [run_id:{self.run_id}] {message}")
def _should_print(self, task):
return hasattr(task, "tags") and "print_action" in task.tags
def _pretty_print(self, result, status):
task_name = result.task_name or result._task.get_name()
host = result._host.get_name()
display.banner(f"TASK [{task_name}]")
display.display(f"{host} | {status}", color="green" if status == "ok" else "red")
display.display(self._dump_results(result._result))
def v2_runner_on_ok(self, result):
task = result.task_name or result._task.get_name()
host = result._host.get_name()
self._log_to_syslog(f"{host} | OK | Task: {task}")
if self._should_print(result._task):
self._pretty_print(result, "ok")
def v2_runner_on_failed(self, result, ignore_errors=False):
task = result.task_name or result._task.get_name()
host = result._host.get_name()
self._log_to_syslog(f"{host} | FAILED | Task: {task}")
if self._should_print(result._task):
self._pretty_print(result, "failed")
def v2_runner_on_skipped(self, result):
task = result.task_name or result._task.get_name()
host = result._host.get_name()
self._log_to_syslog(f"{host} | SKIPPED | Task: {task}")
if self._should_print(result._task):
self._pretty_print(result, "skipped")
def v2_playbook_on_stats(self, stats):
summary = {}
for host in stats.processed.keys():
s = stats.summarize(host)
summary_line = f"{host} | SUMMARY | ok={s['ok']} changed={s['changed']} unreachable={s['unreachable']} failed={s['failures']} skipped={s['skipped']}"
self._log_to_syslog(summary_line)
display.display(summary_line)
display.banner("PLAYBOOK SUMMARY")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment