第一步:Hello world - 让VRL运行起来

日志输入

当用户在在终端输入 “hello”;Vector 的 stdin Source 会把它变成一个日志事件。

为了便于学习,可以先把它理解成:

text
1
2
3
{
  "message": "hello"
}

我们的目标是把事件改成:

text
1
2
3
4
{
  "message": "hello",
  "service": "payment"
}

第一条 VRL 语句

给当前事件增加一个名为 service 的字段, 字段值设置为字符串 payment。

text
1
.service = "payment"
  • “.”:当前正在处理的事件。上面示例是 “message=hello”,这就是当前事件
  • “service” 是字段名,嵌套和 js 对象使用一样, “.parent.child”
  • “.service” 就是指当前事件的 service 字段
  • “.service = “payment””:“=”为赋值符号,把字符串 payment 放入当前事件的 service 字段。

完整的 VRL 示例

yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
sources:
  input:
    type: stdin

transforms:
  add_service:
    type: remap
    inputs:
      - input
    source: |
      .service = "payment"      

sinks:
  output:
    type: console
    inputs:
      - add_service
    encoding:
      codec: json

第二条 VRL 增加多个字段

现在增加三个字段

text
1
2
3
.service = "payment"
.env = "test"
.processed = true

输入事件

text
1
2
3
{
  "message": "hello"
}

输出事件

text
1
2
3
4
5
6
{
  "message": "hello",
  "service": "payment",
  "environment": "test",
  "processed": true
}

VRL 程序由表达式组成

VRL 程序由表达式组成,不同表达式可以通过换行或分号分隔。

方式1,换行写法

text
1
2
.service = "payment"
.environment = "test"

方式2,分号写法:

text
1
.service = "payment"; .environment = "test"
note
为了生产配置可读性,优先使用换行

第二步:三种值的类型

字符串值

text
1
.service = "payment"

布尔值

text
1
.processed = true

整数值

text
1
.retry_count = 3

输出样式

json
1
2
3
4
5
{
  "service": "payment",
  "processed": true,
  "retry_count": 3
}
注意
“值类型" 要注意他的样式,否则输出的值类型将不对,这部分对 Elasticsearch Mapping 非常重要。

第三步:读取已有字段

读取事件

text
1
2
3
# .        当前事件
# message  字段名
.message

把读取结果复制到新字段

text
1
.copy = .message

修改已有字段

同一个赋值语法既可以:

  • 创建不存在的字段;
  • 修改已经存在的字段。

区别只在于字段执行前是否存在。

text
1
.message = "new message"

第四步:临时变量

变量的语法

变量写法,创建一个叫 service 的临时变量, 把字符串 payment 保存进去。

text
1
service = "payment"

变量使用

text
1
2
service = "payment"
.service = service

变量的用途

变量主要保存中间结果

text
1
2
3
original_message = .message
.original_message = original_message
.message = "changed"

根路径整体替换

text
1
. = "hello"

. 属于根路径,上面代码属于“根路径整体替换”

这会把整个当前事件替换成字符串。这不再是增加字段,它是替换根值。