如何整合XQuery脚本统计MarkLogic集群日志关键词匹配总数
MarkLogic集群日志关键词统计XQuery模块
功能说明
批量读取MarkLogic集群所有主机的9005_ErrorLog.txt日志文件,统计其中包含关键词SERVICE-EXIT: ManchesterUnited的总行数,最终返回总匹配次数。
完整代码
xquery version "1.0-ml"; (: 定义要匹配的关键词 :) declare variable $KEYWORD as xs.string := "SERVICE-EXIT: ManchesterUnited"; (: 获取集群所有主机的主机名列表 :) declare function local:get-cluster-hosts() as xs.string* { for $host in admin:get-cluster-config()/hosts/host return $host/host-name/text() }; (: 读取单主机日志并统计关键词匹配次数 :) declare function local:count-matches-on-host($host-name as xs.string) as xs.integer { let $log-path := concat("/var/opt/MarkLogic/Logs/9005_ErrorLog.txt") let $log-content := xdmp:host-file-read($host-name, $log-path, <options><encoding>utf-8</encoding></options>) let $log-lines := fn:tokenize($log-content, "\r?\n") return fn:count($log-lines[fn:contains(., $KEYWORD)]) }; (: 主函数:遍历所有主机统计总次数 :) declare function local:count-total-matches() as xs.integer { let $hosts := local:get-cluster-hosts() let $per-host-counts := for $host in $hosts return local:count-matches-on-host($host) return fn:sum($per-host-counts) }; (: 执行主函数输出结果 :) local:count-total-matches()
代码解释
- 获取集群主机列表:通过
admin:get-cluster-config()读取集群配置,提取所有主机的名称。 - 单主机统计逻辑:使用
xdmp:host-file-read()读取指定主机的日志文件,按行分割后筛选包含关键词的行并计数。 - 总次数统计:遍历所有主机,累加每个主机的匹配次数,返回总和。
注意:请根据实际部署路径调整$log-path的值;执行该模块的用户需拥有集群主机文件读取权限及管理员权限以获取集群配置。
内容的提问来源于stack exchange,提问作者SinghVK
相关产品推荐
相关产品推荐

