kibana运行时字段自动生成解决方案

发表于 2025-11-29
更新于 2025-11-29
分类于 技术专栏
阅读量 7
字数统计 2600

背景

我们用ES来收集日志的时候,可以会把一些常用的字段做成json,有些内容会存在于某个字段,但是我们想基于该字段分析里面的内容,举个例子就是,如果我们在msg中打印这么一句话:

[GET /][648254c8-8846-4c10-bde1-52dc735a2917] [STARTING] processing request

我们想基于这句话抽取出里面访问的path/method等字段,那么在kibana下该怎么做?

当前Kibana版本:v 7.17.8

实现方案

  1. 点击左侧菜单的 Dev Tools

    1. image.png
  2. 找到控制台输入以下命令来重新索引并添加运行时字段: image.png

1PUT (这个填写你收集日志的索引库)**/_mapping 2{ 3 "runtime": { 4 "url_path": { 5 "type": "keyword", 6 "script": { 7 "source": """ 8 if (doc['msg.keyword'].size() > 0) { 9 String msg = doc['msg.keyword'].value; 10 def pattern = /\[GET\s+([^\]]+)\]/; 11 def matcher = pattern.matcher(msg); 12 if (matcher.find()) { 13 String path = matcher.group(1); 14 int queryIndex = path.indexOf('?'); 15 if (queryIndex > 0) { 16 path = path.substring(0, queryIndex); 17 } 18 emit(path); 19 } else { 20 emit('unknown'); 21 } 22 } else { 23 emit('unknown'); 24 } 25 """ 26 } 27 }, 28 "is_starting": { 29 "type": "boolean", 30 "script": { 31 "source": """ 32 if (doc['msg.keyword'].size() > 0) { 33 String msg = doc['msg.keyword'].value; 34 if (msg.contains('[STARTING] processing request')) { 35 emit(true); 36 } else { 37 emit(false); 38 } 39 } else { 40 emit(false); 41 } 42 """ 43 } 44 }, 45 "cost": { 46 "type": "long", 47 "script": { 48 "source": """ 49 if (doc['msg.keyword'].size() > 0) { 50 String msg = doc['msg.keyword'].value; 51 // 匹配 "cost XXXms" 格式 52 def pattern = /cost\s+(\d+)ms/; 53 def matcher = pattern.matcher(msg); 54 if (matcher.find()) { 55 try { 56 emit(Long.parseLong(matcher.group(1))); 57 } catch (NumberFormatException e) { 58 emit(null); 59 } 60 } else { 61 emit(null); 62 } 63 } else { 64 emit(null); 65 } 66 """ 67 } 68 } 69 } 70}

执行成功会提示: image.png

之后重新回到Discover,你就会发现多了个url_path的字段了。 image.png

于是你就可以开心的制作你的图表了。比如刚才的url_path和cost,可以制作出渲染耗时排前面的页面: image.png

公众号关注一波~

微信公众号

关于评论和留言

如果对本文 kibana运行时字段自动生成解决方案 的内容有疑问,请在下面的评论系统中留言,谢谢。

网站源码:linxiaowu66 · 豆米的博客

Follow:linxiaowu66 · Github