-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathREADME.md
2099 lines (1294 loc) · 69 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# OTTL Functions
The following functions are intended to be used in implementations of the OpenTelemetry Transformation Language that
interact with OTel data via the Collector's internal data model, [pdata](https://github.com/open-telemetry/opentelemetry-collector/tree/main/pdata).
This document contains documentation for both types of OTTL functions:
- [Editors](#editors) that transform telemetry.
- [Converters](#converters) that provide utilities for transforming telemetry.
## Design principles
For the standard OTTL functions described in this document, we specify design principles to ensure they are always
secure and safe for use:
- Built-in OTTL functions may not access the file system, network, or any other I/O devices.
- Built-in OTTL functions may share information only through their parameters and results.
- Built-in OTTL functions must be terminating; they must not loop forever.
OTTL functions are implemented in Go, and so are only limited by what can be implemented in a Go program.
User-defined OTTL functions may therefore not adhere the above principles.
## Working with functions
Functions generally expect specific types to be returned by `Paths`.
For these functions, if that type is not returned or if `nil` is returned, the function will error.
Some functions are able to handle different types and will generally convert those types to their desired type.
In these situations the function will error if it does not know how to do the conversion.
Use `ErrorMode` to determine how the `Statement` handles these errors.
See the component-specific guides for how each uses error mode:
- [filterprocessor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/filterprocessor/README.md#configuration)
- [routingconnector](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/connector/routingconnector/README.md#configuration)
- [transformprocessor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/transformprocessor/README.md#config)
## Editors
Editors are what OTTL uses to transform telemetry.
Editors:
- Are allowed to transform telemetry. When a Function is invoked the expectation is that the underlying telemetry is modified in some way.
- May have side effects. Some Functions may generate telemetry and add it to the telemetry payload to be processed in this batch.
- May return values. Although not common and not required, Functions may return values.
Available Editors:
- [append](#append)
- [delete_key](#delete_key)
- [delete_matching_keys](#delete_matching_keys)
- [keep_matching_keys](#keep_matching_keys)
- [flatten](#flatten)
- [keep_keys](#keep_keys)
- [limit](#limit)
- [merge_maps](#merge_maps)
- [replace_all_matches](#replace_all_matches)
- [replace_all_patterns](#replace_all_patterns)
- [replace_match](#replace_match)
- [replace_pattern](#replace_pattern)
- [set](#set)
- [truncate_all](#truncate_all)
### append
`append(target, Optional[value], Optional[values])`
The `append` function appends single or multiple string values to `target`.
`append` converts scalar values into an array if the field exists but is not an array, and creates an array containing the provided values if the field doesn’t exist.
Resulting field is always of type `pcommon.Slice` and will not convert the types of existing or new items in the slice. This means that it is possible to create a slice whose elements have different types. Be careful when using `append` to set attribute values, as this will produce values that are not possible to create through OpenTelemetry APIs [according to](https://opentelemetry.io/docs/specs/otel/common/#attribute) the OpenTelemetry specification.
- `append(attributes["tags"], "prod")`
- `append(attributes["tags"], values = ["staging", "staging:east"])`
- `append(attributes["tags_copy"], attributes["tags"])`
### delete_key
`delete_key(target, key)`
The `delete_key` function removes a key from a `pcommon.Map`
`target` is a path expression to a `pcommon.Map` type field. `key` is a string that is a key in the map.
The key will be deleted from the map.
Examples:
- `delete_key(attributes, "http.request.header.authorization")`
- `delete_key(resource.attributes, "http.request.header.authorization")`
### delete_matching_keys
`delete_matching_keys(target, pattern)`
The `delete_matching_keys` function removes all keys from a `pcommon.Map` that match a regex pattern.
`target` is a path expression to a `pcommon.Map` type field. `pattern` is a regex string.
All keys that match the pattern will be deleted from the map.
Examples:
- `delete_matching_keys(attributes, "(?i).*password.*")`
- `delete_matching_keys(resource.attributes, "(?i).*password.*")`
### keep_matching_keys
`keep_matching_keys(target, pattern)`
The `keep_matching_keys` function keeps all keys from a `pcommon.Map` that match a regex pattern.
`target` is a path expression to a `pcommon.Map` type field. `pattern` is a regex string.
All keys that match the pattern will remain in the map, while non matching keys will be removed.
Examples:
- `keep_matching_keys(attributes, "(?i).*version.*")`
- `keep_matching_keys(resource.attributes, "(?i).*version.*")`
### flatten
`flatten(target, Optional[prefix], Optional[depth])`
The `flatten` function flattens a `pcommon.Map` by moving items from nested maps to the root.
`target` is a path expression to a `pcommon.Map` type field. `prefix` is an optional string. `depth` is an optional non-negative int.
For example, the following map
```json
{
"name": "test",
"address": {
"street": "first",
"house": 1234
},
"occupants": ["user 1", "user 2"]
}
```
is converted to
```json
{
"name": "test",
"address.street": "first",
"address.house": 1234,
"occupants.0": "user 1",
"occupants.1": "user 2"
}
```
If `prefix` is supplied, it will be appended to the start of the new keys. This can help you namespace the changes. For example, if in the above example a `prefix` of `app` was configured, the result would be
```json
{
"app.name": "test",
"app.address.street": "first",
"app.address.house": 1234,
"app.occupants.0": "user 1",
"app.occupants.1": "user 2"
}
```
If `depth` is supplied, the function will only flatten nested maps up to that depth. For example, if a `depth` of `2` was configured, the following map
```json
{
"0": {
"1": {
"2": {
"3": {
"4": "value"
}
}
}
}
}
```
the result would be
```json
{
"0.1.2": {
"3": {
"4": "value"
}
}
}
```
A `depth` of `0` means that no flattening will occur.
Examples:
- `flatten(attributes)`
- `flatten(cache, "k8s", 4)`
- `flatten(body, depth=2)`
### keep_keys
`keep_keys(target, keys[])`
The `keep_keys` function removes all keys from the `pcommon.Map` that do not match one of the supplied keys.
`target` is a path expression to a `pcommon.Map` type field. `keys` is a slice of one or more strings.
The map will be changed to only contain the keys specified by the list of strings.
Examples:
- `keep_keys(attributes, ["http.method"])`
- `keep_keys(resource.attributes, ["http.method", "http.route", "http.url"])`
### limit
`limit(target, limit, priority_keys[])`
The `limit` function reduces the number of elements in a `pcommon.Map` to be no greater than the limit.
`target` is a path expression to a `pcommon.Map` type field. `limit` is a non-negative integer.
`priority_keys` is a list of strings of attribute keys that won't be dropped during limiting.
The number of priority keys must be less than the supplied `limit`.
The map will be mutated such that the number of items does not exceed the limit.
The map is not copied or reallocated.
Which items are dropped is random, provide keys in `priority_keys` to preserve required keys.
Examples:
- `limit(attributes, 100, [])`
- `limit(resource.attributes, 50, ["http.host", "http.method"])`
### merge_maps
`merge_maps(target, source, strategy)`
The `merge_maps` function merges the source map into the target map using the supplied strategy to handle conflicts.
`target` is a `pcommon.Map` type field. `source` is a `pcommon.Map` type field. `strategy` is a string that must be one of `insert`, `update`, or `upsert`.
If strategy is:
- `insert`: Insert the value from `source` into `target` where the key does not already exist.
- `update`: Update the entry in `target` with the value from `source` where the key does exist.
- `upsert`: Performs insert or update. Insert the value from `source` into `target` where the key does not already exist and update the entry in `target` with the value from `source` where the key does exist.
`merge_maps` is a special case of the [`set` function](#set). If you need to completely override `target`, use `set` instead.
Examples:
- `merge_maps(attributes, ParseJSON(body), "upsert")`
- `merge_maps(attributes, ParseJSON(attributes["kubernetes"]), "update")`
- `merge_maps(attributes, resource.attributes, "insert")`
### replace_all_matches
`replace_all_matches(target, pattern, replacement, Optional[function], Optional[replacementFormat])`
The `replace_all_matches` function replaces any matching string value with the replacement string.
`target` is a path expression to a `pcommon.Map` type field. `pattern` is a string following [filepath.Match syntax](https://pkg.go.dev/path/filepath#Match). `replacement` is either a path expression to a string telemetry field or a literal string. `function` is an optional argument that can take in any Converter that accepts a (`replacement`) string and returns a string. An example is a hash function that replaces any matching string with the hash value of `replacement`.
`replacementFormat` is an optional string argument that specifies the format of the replacement. It must contain exactly one `%s` format specifier as shown in the example below. No other format specifiers are supported.
Each string value in `target` that matches `pattern` will get replaced with `replacement`. Non-string values are ignored.
Examples:
- `replace_all_matches(attributes, "/user/*/list/*", "/user/{userId}/list/{listId}")`
- `replace_all_matches(attributes, "/user/*/list/*", "/user/{userId}/list/{listId}", SHA256, "/user/%s")`
### replace_all_patterns
`replace_all_patterns(target, mode, regex, replacement, Optional[function], Optional[replacementFormat])`
The `replace_all_patterns` function replaces any segments in a string value or key that match the regex pattern with the replacement string.
`target` is a path expression to a `pcommon.Map` type field. `regex` is a regex string indicating a segment to replace. `replacement` is either a path expression to a string telemetry field or a literal string.
`mode` determines whether the match and replace will occur on the map's value or key. Valid values are `key` and `value`.
If one or more sections of `target` match `regex` they will get replaced with `replacement`.
The `replacement` string can refer to matched groups using [regexp.Expand syntax](https://pkg.go.dev/regexp#Regexp.Expand). `replacementFormat` is an optional string argument that specifies the format of the replacement. It must contain exactly one `%s` format specifier as shown in the example below. No other format specifiers are supported.
The `function` is an optional argument that can take in any Converter that accepts a (`replacement`) string and returns a string. An example is a hash function that replaces any matching regex pattern with the hash value of `replacement`.
Examples:
- `replace_all_patterns(attributes, "value", "/account/\\d{4}", "/account/{accountId}")`
- `replace_all_patterns(attributes, "key", "/account/\\d{4}", "/account/{accountId}")`
- `replace_all_patterns(attributes, "key", "^kube_([0-9A-Za-z]+_)", "k8s.$$1.")`
- `replace_all_patterns(attributes, "key", "^kube_([0-9A-Za-z]+_)", "$$1.")`
- `replace_all_patterns(attributes, "key", "^kube_([0-9A-Za-z]+_)", "$$1.", SHA256, "k8s.%s")`
Note that when using OTTL within the collector's configuration file, `$` must be escaped to `$$` to bypass
environment variable substitution logic. To input a literal `$` from the configuration file, use `$$$`.
If using OTTL outside of collector configuration, `$` should not be escaped and a literal `$` can be entered using `$$`.
### replace_match
`replace_match(target, pattern, replacement, Optional[function], Optional[replacementFormat])`
The `replace_match` function allows replacing entire strings if they match a glob pattern.
`target` is a path expression to a telemetry field. `pattern` is a string following [filepath.Match syntax](https://pkg.go.dev/path/filepath#Match). `replacement` is either a path expression to a string telemetry field or a literal string.
`replacementFormat` is an optional string argument that specifies the format of the replacement. It must contain exactly one `%s` format specifier as shown in the example below. No other format specifiers are supported.
If `target` matches `pattern` it will get replaced with `replacement`.
The `function` is an optional argument that can take in any Converter that accepts a (`replacement`) string and returns a string. An example is a hash function that replaces any matching glob pattern with the hash value of `replacement`.
Examples:
- `replace_match(attributes["http.target"], "/user/*/list/*", "/user/{userId}/list/{listId}")`
- `replace_match(attributes["http.target"], "/user/*/list/*", "/user/{userId}/list/{listId}", SHA256, "/user/%s")`
### replace_pattern
`replace_pattern(target, regex, replacement, Optional[function], Optional[replacementFormat])`
The `replace_pattern` function allows replacing all string sections that match a regex pattern with a new value.
`target` is a path expression to a telemetry field. `regex` is a regex string indicating a segment to replace. `replacement` is either a path expression to a string telemetry field or a literal string.
If one or more sections of `target` match `regex` they will get replaced with `replacement`.
The `replacement` string can refer to matched groups using [regexp.Expand syntax](https://pkg.go.dev/regexp#Regexp.Expand). `replacementFormat` is an optional string argument that specifies the format of the replacement. It must contain exactly one `%s` format specifier as shown in the example below. No other format specifiers are supported
The `function` is an optional argument that can take in any Converter that accepts a (`replacement`) string and returns a string. An example is a hash function that replaces a matching regex pattern with the hash value of `replacement`.
Examples:
- `replace_pattern(resource.attributes["process.command_line"], "password\\=[^\\s]*(\\s?)", "password=***")`
- `replace_pattern(name, "^kube_([0-9A-Za-z]+_)", "k8s.$$1.")`
- `replace_pattern(name, "^kube_([0-9A-Za-z]+_)", "$$1.", SHA256, "k8s.%s")`
Note that when using OTTL within the collector's configuration file, `$` must be escaped to `$$` to bypass
environment variable substitution logic. To input a literal `$` from the configuration file, use `$$$`.
If using OTTL outside of collector configuration, `$` should not be escaped and a literal `$` can be entered using `$$`.
### set
`set(target, value)`
The `set` function allows users to set a telemetry field using a value.
`target` is a path expression to a telemetry field. `value` is any value type. If `value` resolves to `nil`, e.g. it references an unset map value, there will be no action.
How the underlying telemetry field is updated is decided by the path expression implementation provided by the user to the `ottl.ParseStatements`.
Examples:
- `set(attributes["http.path"], "/foo")`
- `set(name, attributes["http.route"])`
- `set(trace_state["svc"], "example")`
- `set(attributes["source"], trace_state["source"])`
### truncate_all
`truncate_all(target, limit)`
The `truncate_all` function truncates all string values in a `pcommon.Map` so that none are longer than the limit.
`target` is a path expression to a `pcommon.Map` type field. `limit` is a non-negative integer.
The map will be mutated such that the number of characters in all string values is less than or equal to the limit. Non-string values are ignored.
Examples:
- `truncate_all(attributes, 100)`
- `truncate_all(resource.attributes, 50)`
## Converters
Converters are pure functions that take OTTL values as input and output a single value for use within a statement.
Unlike functions, they do not modify any input telemetry and always return a value.
Available Converters:
- [Base64Decode](#base64decode)
- [Decode](#decode)
- [Concat](#concat)
- [ConvertCase](#convertcase)
- [ConvertAttributesToElementsXML](#convertattributestoelementsxml)
- [ConvertTextToElementsXML](#converttexttoelementsxml)
- [Day](#day)
- [Double](#double)
- [Duration](#duration)
- [ExtractPatterns](#extractpatterns)
- [ExtractGrokPatterns](#extractgrokpatterns)
- [FNV](#fnv)
- [Format](#format)
- [GetXML](#getxml)
- [Hex](#hex)
- [Hour](#hour)
- [Hours](#hours)
- [InsertXML](#insertxml)
- [Int](#int)
- [IsBool](#isbool)
- [IsDouble](#isdouble)
- [IsInt](#isint)
- [IsRootSpan](#isrootspan)
- [IsMap](#ismap)
- [IsMatch](#ismatch)
- [IsList](#islist)
- [IsString](#isstring)
- [Len](#len)
- [Log](#log)
- [MD5](#md5)
- [Microseconds](#microseconds)
- [Milliseconds](#milliseconds)
- [Minute](#minute)
- [Minutes](#minutes)
- [Month](#month)
- [Nanoseconds](#nanoseconds)
- [Now](#now)
- [ParseCSV](#parsecsv)
- [ParseJSON](#parsejson)
- [ParseKeyValue](#parsekeyvalue)
- [ParseSimplifiedXML](#parsesimplifiedxml)
- [ParseXML](#parsexml)
- [RemoveXML](#removexml)
- [Seconds](#seconds)
- [SHA1](#sha1)
- [SHA256](#sha256)
- [SHA512](#sha512)
- [Sort](#sort)
- [SpanID](#spanid)
- [Split](#split)
- [String](#string)
- [Substring](#substring)
- [Time](#time)
- [ToKeyValueString](#tokeyvaluestring)
- [TraceID](#traceid)
- [TruncateTime](#truncatetime)
- [Unix](#unix)
- [UnixMicro](#unixmicro)
- [UnixMilli](#unixmilli)
- [UnixNano](#unixnano)
- [UnixSeconds](#unixseconds)
- [UserAgent](#useragent)
- [UUID](#UUID)
- [Year](#year)
### Base64Decode (Deprecated)
*This function has been deprecated. Please use the [Decode](#decode) function instead.*
`Base64Decode(value)`
The `Base64Decode` Converter takes a base64 encoded string and returns the decoded string.
`value` is a valid base64 encoded string.
Examples:
- `Base64Decode("aGVsbG8gd29ybGQ=")`
- `Base64Decode(attributes["encoded field"])`
### Decode
`Decode(value, encoding)`
The `Decode` Converter takes a string or byte array encoded with the specified encoding and returns the decoded string.
`value` is a valid encoded string or byte array.
`encoding` is a valid encoding name included in the [IANA encoding index](https://www.iana.org/assignments/character-sets/character-sets.xhtml).
Examples:
- `Decode("aGVsbG8gd29ybGQ=", "base64")`
- `Decode(attributes["encoded field"], "us-ascii")`
### Concat
`Concat(values[], delimiter)`
The `Concat` Converter takes a sequence of values and a delimiter and concatenates their string representation. Unsupported values, such as lists or maps that may substantially increase payload size, are not added to the resulting string.
`values` is a list of values. It supports paths, primitive values, and byte slices (such as trace IDs or span IDs).
`delimiter` is a string value that is placed between strings during concatenation. If no delimiter is desired, then simply pass an empty string.
Examples:
- `Concat([attributes["http.method"], attributes["http.path"]], ": ")`
- `Concat([name, 1], " ")`
- `Concat(["HTTP method is: ", attributes["http.method"]], "")`
### ConvertCase
`ConvertCase(target, toCase)`
The `ConvertCase` Converter converts the `target` string into the desired case `toCase`.
`target` is a string. `toCase` is a string.
If the `target` is not a string or does not exist, the `ConvertCase` Converter will return an error.
`toCase` can be:
- `lower`: Converts the `target` string to lowercase (e.g. `MY_METRIC` to `my_metric`)
- `upper`: Converts the `target` string to uppercase (e.g. `my_metric` to `MY_METRIC`)
- `snake`: Converts the `target` string to snakecase (e.g. `myMetric` to `my_metric`)
- `camel`: Converts the `target` string to camelcase (e.g. `my_metric` to `MyMetric`)
If `toCase` is any value other than the options above, the `ConvertCase` Converter will return an error during collector startup.
Examples:
- `ConvertCase(metric.name, "snake")`
### ConvertAttributesToElementsXML
`ConvertAttributesToElementsXML(target, Optional[xpath])`
The `ConvertAttributesToElementsXML` Converter returns an edited version of an XML string where attributes are converted into child elements.
`target` is a Getter that returns a string. This string should be in XML format.
If `target` is not a string, nil, or cannot be parsed as XML, `ConvertAttributesToElementsXML` will return an error.
`xpath` (optional) is a string that specifies an [XPath](https://www.w3.org/TR/1999/REC-xpath-19991116/) expression that
selects one or more elements. Attributes will only be converted within the result(s) of the xpath.
For example, `<a foo="bar"><b>baz</b></a>` will be converted to `<a><b>baz</b><foo>bar</foo></a>`.
Examples:
Convert all attributes in a document
- `ConvertAttributesToElementsXML(body)`
Convert only attributes within "Record" elements
- `ConvertAttributesToElementsXML(body, "/Log/Record")`
### ConvertTextToElementsXML
`ConvertTextToElementsXML(target, Optional[xpath], Optional[elementName])`
The `ConvertTextToElementsXML` Converter returns an edited version of an XML string where all text belongs to a dedicated element.
`target` is a Getter that returns a string. This string should be in XML format.
If `target` is not a string, nil, or cannot be parsed as XML, `ConvertTextToElementsXML` will return an error.
`xpath` (optional) is a string that specifies an [XPath](https://www.w3.org/TR/1999/REC-xpath-19991116/) expression that
selects one or more elements. Content will only be converted within the result(s) of the xpath. The default is `/`.
`elementName` (optional) is a string that is used for any element tags that are created to wrap content.
The default is `"value"`.
For example, `<a><b>foo</b>bar</a>` will be converted to `<a><b>foo</b><value>bar</value></a>`.
Examples:
Ensure all text content in a document is wrapped in a dedicated element
- `ConvertTextToElementsXML(body)`
Use a custom name for any new elements
- `ConvertTextToElementsXML(body, elementName = "custom")`
Convert only part of the document
- `ConvertTextToElementsXML(body, "/some/part/", "value")`
### Day
`Day(value)`
The `Day` Converter returns the day component from the specified time using the Go stdlib [`time.Day` function](https://pkg.go.dev/time#Time.Day).
`value` is a `time.Time`. If `value` is another type, an error is returned.
The returned type is `int64`.
Examples:
- `Day(Now())`
### Double
The `Double` Converter converts an inputted `value` into a double.
The returned type is float64.
The input `value` types:
* float64. returns the `value` without changes.
* string. Tries to parse a double from string. If it fails then nil will be returned.
* bool. If `value` is true, then the function will return 1 otherwise 0.
* int64. The function converts the integer to a double.
If `value` is another type or parsing failed nil is always returned.
The `value` is either a path expression to a telemetry field to retrieve or a literal.
Examples:
- `Double(attributes["http.status_code"])`
- `Double("2.0")`
### Duration
`Duration(duration)`
The `Duration` Converter takes a string representation of a duration and converts it to a [Golang `time.duration`](https://pkg.go.dev/time#ParseDuration).
`duration` is a string. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
If either `duration` is nil or is in a format that cannot be converted to Golang `time.duration`, an error is returned.
Examples:
- `Duration("3s")`
- `Duration("333ms")`
- `Duration("1000000h")`
### ExtractPatterns
`ExtractPatterns(target, pattern)`
The `ExtractPatterns` Converter returns a `pcommon.Map` struct that is a result of extracting named capture groups from the target string. If not matches are found then an empty `pcommon.Map` is returned.
`target` is a Getter that returns a string. `pattern` is a regex string.
If `target` is not a string or nil `ExtractPatterns` will return an error. If `pattern` does not contain at least 1 named capture group then `ExtractPatterns` will error on startup.
Examples:
- `ExtractPatterns(attributes["k8s.change_cause"], "GIT_SHA=(?P<git.sha>\w+)")`
- `ExtractPatterns(body, "^(?P<timestamp>\\w+ \\w+ [0-9]+:[0-9]+:[0-9]+) (?P<hostname>([A-Za-z0-9-_]+)) (?P<process>\\w+)(\\[(?P<pid>\\d+)\\])?: (?P<message>.*)$")`
### ExtractGrokPatterns
`ExtractGrokPatterns(target, pattern, Optional[namedCapturesOnly], Optional[patternDefinitions])`
The `ExtractGrokPatterns` Converter parses unstructured data into a format that is structured and queryable.
It returns a `pcommon.Map` struct that is a result of extracting named capture groups from the target string. If no matches are found then an empty `pcommon.Map` is returned.
- `target` is a Getter that returns a string.
- `pattern` is a grok pattern string.
- `namedCapturesOnly` (optional) specifies if non-named captures should be returned.
- `patternDefinitions` (optional) is a list of custom pattern definition strings used inside `pattern` in the form of `PATTERN_NAME=PATTERN`.
This parameter lets you define your own custom patterns to improve readability when the extracted `pattern` is not part of the default set or when you need custom naming.
If `target` is not a string or nil `ExtractGrokPatterns` returns an error. If `pattern` does not contain at least 1 named capture group and `namedCapturesOnly` is set to `true` then `ExtractPatterns` errors on startup.
Parsing is done using [Elastic Go-Grok](https://github.com/elastic/go-grok?tab=readme-ov-file) library.
Grok is a regular expression dialect that supports reusable aliased expressions. It sits on `re2` regex library so any valid `re2` expressions are valid in grok.
Grok uses this regular expression language to allow naming existing patterns and combining them into more complex patterns that match your fields
Pattern can be specified in either of these forms:
- `%{SYNTAX}` - e.g {NUMBER}
- `%{SYNTAX:ID}` - e.g {NUMBER:MY_AGE}
- `%{SYNTAX:ID:TYPE}` - e.g {NUMBER:MY_AGE:INT}
Where `SYNTAX` is a pattern that will match your text, `ID` is identifier you give to the piece of text being matched and `TYPE` data type you want to cast your named field.
Supported types are `int`, `long`, `double`, `float` and boolean
The [Elastic Go-Grok](https://github.com/elastic/go-grok) ships with numerous predefined grok patterns that simplify working with grok.
In collector Complete set is included consisting of a default set and all additional sets adding product/tool specific capabilities (like [aws](https://github.com/elastic/go-grok/blob/main/patterns/aws.go) or [java](https://github.com/elastic/go-grok/blob/main/patterns/java.go) patterns).
Default set consists of:
| Name | Example |
|-----|-----|
| WORD | "hello", "world123", "test_data" |
| NOTSPACE | "example", "text-with-dashes", "12345" |
| SPACE | " ", "\t", " " |
| INT | "123", "-456", "+789" |
| NUMBER | "123", "456.789", "-0.123" |
| BOOL |"true", "false", "true" |
| BASE10NUM | "123", "-123.456", "0.789" |
| BASE16NUM | "1a2b", "0x1A2B", "-0x1a2b3c" |
| BASE16FLOAT | "0x1.a2b3", "-0x1A2B3C.D" |
| POSINT | "123", "456", "789" |
| NONNEGINT | "0", "123", "456" |
| GREEDYDATA |"anything goes", "literally anything", "123 #@!" |
| QUOTEDSTRING | "\"This is a quote\"", "'single quoted'" |
| UUID |"123e4567-e89b-12d3-a456-426614174000" |
| URN | "urn:isbn:0451450523", "urn:ietf:rfc:2648" |
and many more. Complete list can be found [here](https://github.com/elastic/go-grok/blob/main/patterns/default.go).
Examples:
- _Uses regex pattern with named captures to extract_:
`ExtractGrokPatterns(attributes["k8s.change_cause"], "GIT_SHA=(?P<git.sha>\w+)")`
- _Uses regex pattern with named captures to extract_:
`ExtractGrokPatterns(body, "^(?P<timestamp>\\w+ \\w+ [0-9]+:[0-9]+:[0-9]+) (?P<hostname>([A-Za-z0-9-_]+)) (?P<process>\\w+)(\\[(?P<pid>\\d+)\\])?: (?P<message>.*)$")`
- _Uses `URI` from default set to extract URI and includes only named captures_:
`ExtractGrokPatterns(body, "%{URI}", true)`
- _Uses more complex pattern consisting of elements from default set and includes only named captures_:
`ExtractGrokPatterns(body, "%{DATESTAMP:timestamp} %{TZ:event.timezone} %{DATA:user.name} %{GREEDYDATA:postgresql.log.connection_id} %{POSINT:process.pid:int}", true)`
- _Uses `LOGLINE` pattern defined in `patternDefinitions` passed as last argument_:
`ExtractGrokPatterns(body, "%{LOGLINE}", true, ["LOGLINE=%{DATESTAMP:timestamp} %{TZ:event.timezone} %{DATA:user.name} %{GREEDYDATA:postgresql.log.connection_id} %{POSINT:process.pid:int}"])`
- Add custom patterns to parse the password from `/etc/passwd` and making `pattern` readable:
- `pattern`: `%{USERNAME:user.name}:%{PASSWORD:user.password}:%{USERINFO}`
- `patternDefinitions`:
- `PASSWORD=%{WORD}`
- `USERINFO=%{GREEDYDATA}`
Note that `USERNAME` is in the default pattern set and does not need to be redefined.
- Target: `smith:pass123:1001:1000:J Smith,1234,(234)567-8910,(234)567-1098,email:/home/smith:/bin/sh`
- Return values:
- `user.name`: smith
- `user.password`: pass123
### FNV
`FNV(value)`
The `FNV` Converter converts the `value` to an FNV hash/digest.
The returned type is int64.
`value` is either a path expression to a string telemetry field or a literal string. If `value` is another type an error is returned.
If an error occurs during hashing it will be returned.
Examples:
- `FNV(attributes["device.name"])`
- `FNV("name")`
### Format
```Format(formatString, []formatArguments)```
The `Format` Converter takes the given format string and formats it using `fmt.Sprintf` and the given arguments.
`formatString` is a string. `formatArguments` is an array of values.
If the `formatString` is not a string or does not exist, the `Format` Converter will return an error.
If any of the `formatArgs` are incorrect (e.g. missing, or an incorrect type for the corresponding format specifier), then a string will still be returned, but with Go's default error handling for `fmt.Sprintf`.
Format specifiers that can be used in `formatString` are documented in Go's [fmt package documentation](https://pkg.go.dev/fmt#hdr-Printing)
Examples:
- `Format("%02d", [attributes["priority"]])`
- `Format("%04d-%02d-%02d", [Year(Now()), Month(Now()), Day(Now())])`
- `Format("%s/%s/%04d-%02d-%02d.log", [attributes["hostname"], body["program"], Year(Now()), Month(Now()), Day(Now())])`
### GetXML
`GetXML(target, xpath)`
The `GetXML` Converter returns an XML string with selected elements.
`target` is a Getter that returns a string. This string should be in XML format.
If `target` is not a string, nil, or is not valid xml, `GetXML` will return an error.
`xpath` is a string that specifies an [XPath](https://www.w3.org/TR/1999/REC-xpath-19991116/) expression that
selects one or more elements. Currently, this converter only supports selecting elements.
Examples:
Get all elements at the root of the document with tag "a"
- `GetXML(body, "/a")`
Gel all elements anywhere in the document with tag "a"
- `GetXML(body, "//a")`
Get the first element at the root of the document with tag "a"
- `GetXML(body, "/a[1]")`
Get all elements in the document with tag "a" that have an attribute "b" with value "c"
- `GetXML(body, "//a[@b='c']")`
### Hex
`Hex(value)`
The `Hex` converter converts the `value` to its hexadecimal representation.
The returned type is string representation of the hexadecimal value.
The input `value` types:
- float64 (`1.1` will result to `0x3ff199999999999a`)
- string (`"1"` will result in `0x31`)
- bool (`true` will result in `0x01`; `false` to `0x00`)
- int64 (`12` will result in `0xC`)
- []byte (without any changes - `0x02` will result to `0x02`)
If `value` is another type or parsing failed nil is always returned.
The `value` is either a path expression to a telemetry field to retrieve or a literal.
Examples:
- `Hex(attributes["http.status_code"])`
- `Hex(2.0)`
### Hour
`Hour(value)`
The `Hour` Converter returns the hour from the specified time. The Converter [uses the `time.Hour` function](https://pkg.go.dev/time#Time.Hour).
`value` is a `time.Time`. If `value` is another type an error is returned.
The returned type is `int64`.
Examples:
- `Hour(Now())`
### Hours
`Hours(value)`
The `Hours` Converter returns the duration as a floating point number of hours.
`value` is a `time.Duration`. If `value` is another type an error is returned.
The returned type is `float64`.
Examples:
- `Hours(Duration("1h"))`
### InsertXML
`InsertXML(target, xpath, value)`
The `InsertXML` Converter returns an edited version of an XML string with child elements added to selected elements.
`target` is a Getter that returns a string. This string should be in XML format and represents the document which will
be modified. If `target` is not a string, nil, or is not valid xml, `InsertXML` will return an error.
`xpath` is a string that specifies an [XPath](https://www.w3.org/TR/1999/REC-xpath-19991116/) expression that
selects one or more elements.
`value` is a Getter that returns a string. This string should be in XML format and represents the document which will
be inserted into `target`. If `value` is not a string, nil, or is not valid xml, `InsertXML` will return an error.
Examples:
Add an element "foo" to the root of the document
- `InsertXML(body, "/", "<foo/>")`
Add an element "bar" to any element called "foo"
- `InsertXML(body, "//foo", "<bar/>")`
Fetch and insert an xml document into another
- `InsertXML(body, "/subdoc", attributes["subdoc"])`
### Int
`Int(value)`
The `Int` Converter converts the `value` to int type.
The returned type is int64.
The input `value` types:
- float64. Fraction is discharged (truncation towards zero).
- string. Trying to parse an integer from string if it fails then nil will be returned.
- bool. If `value` is true, then the function will return 1 otherwise 0.
- int64. The function returns the `value` without changes.
If `value` is another type or parsing failed nil is always returned.
The `value` is either a path expression to a telemetry field to retrieve or a literal.
Examples:
- `Int(attributes["http.status_code"])`
- `Int("2.0")`
### IsBool
`IsBool(value)`
The `IsBool` Converter evaluates whether the given `value` is a boolean or not.
Specifically, it will return `true` if the provided `value` is one of the following:
1. A Go's native `bool` type.
2. A `pcommon.ValueTypeBool`.
Otherwise, it will return `false`.
Examples:
- `IsBool(false)`
- `IsBool(pcommon.NewValueBool(false))`
- `IsBool(42)`
- `IsBool(attributes["any key"])`
### IsDouble
`IsDouble(value)`
The `IsDouble` Converter returns true if the given value is a double.
The `value` is either a path expression to a telemetry field to retrieve, or a literal.
If `value` is a `float64` or a `pcommon.ValueTypeDouble` then returns `true`, otherwise returns `false`.
Examples:
- `IsDouble(body)`
- `IsDouble(attributes["maybe a double"])`
### IsInt
`IsInt(value)`
The `IsInt` Converter returns true if the given value is a int.
The `value` is either a path expression to a telemetry field to retrieve, or a literal.
If `value` is a `int64` or a `pcommon.ValueTypeInt` then returns `true`, otherwise returns `false`.
Examples: