InterpolateFields replaces all occurrences of field modifiers in the given string with values extracted from the event. Field modifiers may contain a leading ordinal which refers to the event in particular sequence stage. Otherwise, the modifier is a well-known field name prepended with the `%` symb
(s string, evts []*event.Event)
| 421 | // which refers to the event in particular sequence stage. Otherwise, the modifier is |
| 422 | // a well-known field name prepended with the `%` symbol. |
| 423 | func InterpolateFields(s string, evts []*event.Event) string { |
| 424 | var fieldsReplRegexp = regexp.MustCompile(`%([1-9]?)\.?([a-z0-9A-Z\[\]._]+)`) |
| 425 | matches := fieldsReplRegexp.FindAllStringSubmatch(s, -1) |
| 426 | r := s |
| 427 | if len(matches) == 0 { |
| 428 | return s |
| 429 | } |
| 430 | |
| 431 | split := func(s string) (string, string) { |
| 432 | n, m := strings.Index(s, "["), strings.Index(s, "]") |
| 433 | if n < 0 || m < 0 { |
| 434 | return s, "" |
| 435 | } |
| 436 | if n > m { |
| 437 | return s, "" |
| 438 | } |
| 439 | return s[0:n], s[n+1 : m] |
| 440 | } |
| 441 | |
| 442 | for _, m := range matches { |
| 443 | switch { |
| 444 | case len(m) == 3: |
| 445 | // parse index if the field modifier |
| 446 | // refers to the event in the sequence |
| 447 | i := 1 |
| 448 | if m[1] != "" { |
| 449 | var err error |
| 450 | i, err = strconv.Atoi(m[1]) |
| 451 | if err != nil { |
| 452 | continue |
| 453 | } |
| 454 | } |
| 455 | if i-1 > len(evts)-1 { |
| 456 | continue |
| 457 | } |
| 458 | evt := evts[i-1] |
| 459 | // extract field value from the event and replace in string |
| 460 | var val any |
| 461 | for _, accessor := range GetAccessors() { |
| 462 | name, arg := split(m[2]) |
| 463 | f := Field{Value: m[2], Name: fields.Field(name), Arg: arg} |
| 464 | var err error |
| 465 | val, err = accessor.Get(f, evt) |
| 466 | if err != nil { |
| 467 | continue |
| 468 | } |
| 469 | if val != nil { |
| 470 | break |
| 471 | } |
| 472 | } |
| 473 | if val != nil { |
| 474 | r = strings.ReplaceAll(r, m[0], fmt.Sprintf("%v", val)) |
| 475 | } else { |
| 476 | r = strings.ReplaceAll(r, m[0], "N/A") |
| 477 | } |
| 478 | default: |
| 479 | return r |
| 480 | } |