如何在Perl中提取命令输出的gatewayName与failed状态并发送邮件?
问题解决思路与优化代码
1. 提取失败网关信息的核心逻辑
要精准匹配每个失败网关的gatewayName和对应的statusCode: "failed",可以通过记录最近的网关名,遇到失败时关联绑定的方式实现——因为命令输出通常按每个网关的信息组排列,这种方式能保证信息对应不错位。
命令输出示例(假设结构)
gatewayName: "PayPal_GW" statusCode: "success" responseTime: 120ms gatewayName: "Stripe_GW" statusCode: "failed" errorMsg: "Connection timeout" gatewayName: "Alipay_GW" statusCode: "failed" errorMsg: "Auth failed"
2. 优化后的Perl代码实现
以下代码会遍历命令输出,实时记录当前网关名称,检测到失败状态时立即关联,最后可按需选择发送汇总邮件或批次邮件:
#!/usr/bin/perl use strict; use warnings; # 存储失败的网关信息 my @failed_gateways; my $current_gateway; # 读取命令输出(支持管道输入或文件读取) while (my $line = <>) { chomp $line; # 提取当前网关名称 if ($line =~ /gatewayName:\s*"([^"]+)"/) { $current_gateway = $1; } # 检测失败状态,绑定当前网关 if ($line =~ /statusCode:\s*"failed"/ && defined $current_gateway) { push @failed_gateways, $current_gateway; # 若需按批次发送邮件,取消下方注释即可 # send_batch_email($current_gateway); } } # 汇总邮件逻辑:存在失败网关时发送清单 if (@failed_gateways) { my $summary = "以下网关执行失败:\n" . join("\n", map { "- $_" } @failed_gateways); send_summary_email($summary); } # 汇总邮件发送函数(需替换为实际环境的邮件逻辑) sub send_summary_email { my ($content) = @_; # 示例:用系统mail命令发送,或使用Mail::Sender模块 print "发送汇总邮件:\n$content\n"; } # 批次邮件发送函数 sub send_batch_email { my ($gateway) = @_; print "发送批次通知: 网关 $gateway 执行失败\n"; }
3. 关键优化点
- 精准关联信息:通过实时记录当前网关名,确保失败状态能准确绑定到对应的网关,避免信息错位。
- 双模式可选:
- 汇总模式:遍历完所有输出后,一次性发送所有失败网关的清单。
- 批次模式:每检测到一个失败网关就立即发送单条通知,只需取消
send_batch_email的注释即可。
- 鲁棒性处理:增加
defined $current_gateway判断,避免出现无网关名的无效失败记录。
内容的提问来源于stack exchange,提问作者user1026398
相关产品推荐
相关产品推荐

