如何在自定义Rundeck插件运行时添加日志监听器捕获远程命令输出
在Rundeck自定义插件中动态添加日志监听器
完全可以在自定义插件运行时动态添加日志监听器捕获输出,无需依赖用户预定义的LogFilterPlugin列表。核心思路是通过Rundeck提供的ExecutionContext获取LogDispatcher,在插件执行期间注册自定义的LogListener,执行完成后再移除监听器即可。
实现步骤与代码示例
自定义LogListener实现类
实现LogListener接口,在logEvent方法中解析日志消息并执行对应操作:import com.dtolabs.rundeck.core.execution.loging.LogEvent; import com.dtolabs.rundeck.core.execution.loging.LogListener; public class CustomLogListener implements LogListener { @Override public void logEvent(final LogEvent event) { // 根据需求解析日志消息 String logMsg = event.getMessage(); if (logMsg.contains("[ACTION_TRIGGER]")) { // 执行你需要的操作,比如触发回调、更新状态等 handleTriggerAction(logMsg); } } private void handleTriggerAction(String msg) { // 自定义业务逻辑实现 System.out.println("捕获到触发指令: " + msg); } }在插件中动态注册/移除监听器
在自定义NodeStepPlugin的executeNodeStep方法中,利用ExecutionContext获取LogDispatcher,完成监听器的注册、使用与清理:import com.dtolabs.rundeck.core.common.INodeEntry; import com.dtolabs.rundeck.core.execution.ExecutionContext; import com.dtolabs.rundeck.core.execution.workflow.steps.StepException; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepPlugin; import com.dtolabs.rundeck.core.plugins.Plugin; import java.util.Map; @Plugin(name = "custom-remote-cmd", service = "NodeStep") public class CustomRemoteCommandPlugin implements NodeStepPlugin { @Override public void executeNodeStep(final ExecutionContext context, final Map<String, Object> configuration, final INodeEntry node) throws StepException { CustomLogListener logListener = new CustomLogListener(); // 注册监听器 context.getLogDispatcher().addLogListener(logListener); try { // 执行你的远程命令逻辑,比如调用SSH工具执行命令 // 这里模拟远程命令输出日志 runRemoteCommand(context); } finally { // 必须在finally块移除监听器,避免内存泄漏或影响后续步骤 context.getLogDispatcher().removeLogListener(logListener); } } private void runRemoteCommand(ExecutionContext context) { // 模拟远程命令输出的日志内容 context.getLogDispatcher().log(0, "远程命令执行中..."); context.getLogDispatcher().log(0, "[ACTION_TRIGGER] 备份数据库"); context.getLogDispatcher().log(0, "远程命令执行完成"); } }
关键注意事项
- 监听器生命周期管理:一定要在
finally块中移除监听器,防止监听器被重复注册,避免内存泄漏或干扰后续步骤的日志处理。 - 异步日志处理:如果你的远程命令是异步执行的,需要确保在所有日志输出完成后再移除监听器,可通过等待命令执行完成的逻辑实现。
- 线程安全:
LogEvent的处理逻辑要保证线程安全,因为日志分发可能是异步多线程的。
内容的提问来源于stack exchange,提问作者Shatazone
相关产品推荐
相关产品推荐

