Skip to content

Commit 9398c4c

Browse files
authored
[pkg/ottl] Add Sprintf OTTL Converter (#33589)
**Description:** This adds in a converter that calls `fmt.Sprintf` with a format string and a set of arguments. **Link to tracking Issue:** #33405 **Testing:** Added in a couple of unit tests **Documentation:** Added the new converter to the functions readme Signed-off-by: sinkingpoint <[email protected]>
1 parent f9cd72a commit 9398c4c

File tree

6 files changed

+177
-0
lines changed

6 files changed

+177
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: enhancement
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
7+
component: pkg/ottl
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: Adds an `Format` function to OTTL that calls `fmt.Sprintf`
11+
12+
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
13+
issues: [33405]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext:
19+
20+
# If your change doesn't affect end users or the exported elements of any package,
21+
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
22+
# Optional: The change log or logs in which this entry should be included.
23+
# e.g. '[user]' or '[user, api]'
24+
# Include 'user' if the change is relevant to end users.
25+
# Include 'api' if there is a change to a library API.
26+
# Default: '[user]'
27+
change_logs: []

pkg/ottl/e2e/e2e_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,12 @@ func Test_e2e_converters(t *testing.T) {
384384
tCtx.GetLogRecord().Attributes().PutInt("test", 266877920130663416)
385385
},
386386
},
387+
{
388+
statement: `set(attributes["test"], Format("%03d-%s", [7, "test"]))`,
389+
want: func(tCtx ottllog.TransformContext) {
390+
tCtx.GetLogRecord().Attributes().PutStr("test", "007-test")
391+
},
392+
},
387393
{
388394
statement: `set(attributes["test"], Hour(Time("12", "%H")))`,
389395
want: func(tCtx ottllog.TransformContext) {

pkg/ottl/ottlfuncs/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,7 @@ Available Converters:
415415
- [Day](#day)
416416
- [ExtractPatterns](#extractpatterns)
417417
- [FNV](#fnv)
418+
- [Format](#format)
418419
- [Hex](#hex)
419420
- [Hour](#hour)
420421
- [Hours](#hours)
@@ -606,6 +607,25 @@ Examples:
606607

607608
- `FNV("name")`
608609

610+
### Format
611+
612+
```Format(formatString, []formatArguments)```
613+
614+
The `Format` Converter takes the given format string and formats it using `fmt.Sprintf` and the given arguments.
615+
616+
`formatString` is a string. `formatArguments` is an array of values.
617+
618+
If the `formatString` is not a string or does not exist, the `Format` Converter will return an error.
619+
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`.
620+
621+
Format specifiers that can be used in `formatString` are documented in Go's [fmt package documentation](https://pkg.go.dev/fmt#hdr-Printing)
622+
623+
Examples:
624+
625+
- `Format("%02d", [attributes["priority"]])`
626+
- `Format("%04d-%02d-%02d", [Year(Now()), Month(Now()), Day(Now())])`
627+
- `Format("%s/%s/%04d-%02d-%02d.log", [attributes["hostname"], body["program"], Year(Now()), Month(Now()), Day(Now())])`
628+
609629
### Hex
610630

611631
`Hex(value)`

pkg/ottl/ottlfuncs/func_format.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"
5+
6+
import (
7+
"context"
8+
"fmt"
9+
10+
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
11+
)
12+
13+
type FormatArguments[K any] struct {
14+
Format string
15+
Vals []ottl.Getter[K]
16+
}
17+
18+
func NewFormatFactory[K any]() ottl.Factory[K] {
19+
return ottl.NewFactory("Format", &FormatArguments[K]{}, createFormatFunction[K])
20+
}
21+
22+
func createFormatFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
23+
args, ok := oArgs.(*FormatArguments[K])
24+
if !ok {
25+
return nil, fmt.Errorf("FormatFactory args must be of type *FormatArguments[K]")
26+
}
27+
28+
return format(args.Format, args.Vals), nil
29+
}
30+
31+
func format[K any](formatString string, vals []ottl.Getter[K]) ottl.ExprFunc[K] {
32+
return func(ctx context.Context, tCtx K) (any, error) {
33+
formatArgs := make([]any, 0, len(vals))
34+
for _, arg := range vals {
35+
formatArg, err := arg.Get(ctx, tCtx)
36+
if err != nil {
37+
return nil, err
38+
}
39+
40+
formatArgs = append(formatArgs, formatArg)
41+
}
42+
43+
return fmt.Sprintf(formatString, formatArgs...), nil
44+
}
45+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package ottlfuncs
5+
6+
import (
7+
"context"
8+
"errors"
9+
"testing"
10+
11+
"github.com/stretchr/testify/assert"
12+
13+
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
14+
)
15+
16+
type getterFunc[K any] func(ctx context.Context, tCtx K) (any, error)
17+
18+
func (g getterFunc[K]) Get(ctx context.Context, tCtx K) (any, error) {
19+
return g(ctx, tCtx)
20+
}
21+
22+
func Test_Format(t *testing.T) {
23+
tests := []struct {
24+
name string
25+
formatString string
26+
formatArgs []ottl.Getter[any]
27+
expected string
28+
}{
29+
{
30+
name: "non formatting string",
31+
formatString: "test",
32+
formatArgs: []ottl.Getter[any]{},
33+
expected: "test",
34+
},
35+
{
36+
name: "padded int",
37+
formatString: "test-%04d",
38+
formatArgs: []ottl.Getter[any]{
39+
getterFunc[any](func(_ context.Context, _ any) (any, error) {
40+
return 2, nil
41+
}),
42+
},
43+
expected: "test-0002",
44+
},
45+
{
46+
name: "multiple-args",
47+
formatString: "test-%04d-%4s",
48+
formatArgs: []ottl.Getter[any]{
49+
getterFunc[any](func(_ context.Context, _ any) (any, error) {
50+
return 2, nil
51+
}),
52+
getterFunc[any](func(_ context.Context, _ any) (any, error) {
53+
return "te", nil
54+
}),
55+
},
56+
expected: "test-0002- te",
57+
},
58+
}
59+
60+
for _, tt := range tests {
61+
t.Run(tt.name, func(t *testing.T) {
62+
exprFunc := format(tt.formatString, tt.formatArgs)
63+
result, err := exprFunc(nil, nil)
64+
assert.NoError(t, err)
65+
assert.Equal(t, tt.expected, result)
66+
})
67+
}
68+
}
69+
70+
func TestFormat_error(t *testing.T) {
71+
target := getterFunc[any](func(_ context.Context, _ any) (any, error) {
72+
return nil, errors.New("failed to get")
73+
})
74+
75+
exprFunc := format[any]("test-%d", []ottl.Getter[any]{target})
76+
_, err := exprFunc(context.Background(), nil)
77+
assert.Error(t, err)
78+
}

pkg/ottl/ottlfuncs/functions.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ func converters[K any]() []ottl.Factory[K] {
7272
NewSHA256Factory[K](),
7373
NewSpanIDFactory[K](),
7474
NewSplitFactory[K](),
75+
NewFormatFactory[K](),
7576
NewStringFactory[K](),
7677
NewSubstringFactory[K](),
7778
NewTimeFactory[K](),

0 commit comments

Comments
 (0)