-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Loki Exporter - Adding a feature for loki exporter to encode JSON for log entry #5846
Merged
Merged
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
491e6e1
initial commit
crearys 18d1808
revert un-needed changes
crearys 403b6a1
test json encode as entry
crearys 4c695b7
add encoding files
crearys caa4507
merge loki encoding with the resource atttribute branch
crearys 071a13c
add format option to loki exporter config
crearys bb37818
add test for loki/json test data
crearys 728f4bf
improve variable names and comments
crearys bf30cc5
pull from upstream main and update loki exporter files to fix tests
crearys bb253b3
Create feature for loki exporter to encode json
crearys 11d5439
mapping convert functions
crearys fcdb38b
Fix linting errors
crearys e01ed0f
Merge remote-tracking branch 'upstream/main' into lokiencoding-pr
crearys ebdcccb
update pdata package
crearys 45a52eb
pull upstream
crearys e80de58
update to use otel 0.36
crearys 3d9ef4f
Merge branch 'lokiencoding-pr' of https://github.com/crearys/opentele…
gillg fc0c481
Merge branch 'main' of https://github.com/open-telemetry/opentelemetr…
gillg 3139761
Add resources in encoded json structure
gillg 7fd92f5
Add missing licence
gillg a855093
Fix review
gillg 30edcbe
Group similar errors
gillg 0edc8fb
Fix serialization
gillg 42d664c
Add a test for unsuported body type
gillg f2f50d6
Fix tests
gillg 7e7fa2f
Merge branch 'main' of https://github.com/open-telemetry/opentelemetr…
gillg 3d11fb3
Fix lint
gillg 119a6a6
Change error level to debug for dropped logs to avoid flood, keeping …
gillg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package lokiexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/lokiexporter" | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
|
||
"go.opentelemetry.io/collector/model/pdata" | ||
) | ||
|
||
// JSON representation of the LogRecord as described by https://developers.google.com/protocol-buffers/docs/proto3#json | ||
|
||
type lokiEntry struct { | ||
Name string `json:"name,omitempty"` | ||
Body string `json:"body,omitempty"` | ||
TraceID string `json:"traceid,omitempty"` | ||
SpanID string `json:"spanid,omitempty"` | ||
Severity string `json:"severity,omitempty"` | ||
Attributes map[string]interface{} `json:"attributes,omitempty"` | ||
Resources map[string]interface{} `json:"resources,omitempty"` | ||
} | ||
|
||
func serializeBody(body pdata.AttributeValue) (string, error) { | ||
str := "" | ||
var err error | ||
if body.Type() == pdata.AttributeValueTypeString { | ||
str = body.StringVal() | ||
} else { | ||
err = fmt.Errorf("unsuported body type to serialize") | ||
} | ||
return str, err | ||
} | ||
|
||
func encodeJSON(lr pdata.LogRecord, res pdata.Resource) (string, error) { | ||
var logRecord lokiEntry | ||
var jsonRecord []byte | ||
var err error | ||
var body string | ||
|
||
body, err = serializeBody(lr.Body()) | ||
if err != nil { | ||
return "", err | ||
} | ||
logRecord = lokiEntry{ | ||
Name: lr.Name(), | ||
Body: body, | ||
TraceID: lr.TraceID().HexString(), | ||
SpanID: lr.SpanID().HexString(), | ||
Severity: lr.SeverityText(), | ||
Attributes: lr.Attributes().AsRaw(), | ||
Resources: res.Attributes().AsRaw(), | ||
} | ||
lr.Body().Type() | ||
|
||
jsonRecord, err = json.Marshal(logRecord) | ||
if err != nil { | ||
return "", err | ||
} | ||
return string(jsonRecord), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package lokiexporter | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"go.opentelemetry.io/collector/model/pdata" | ||
) | ||
|
||
func exampleLog() (pdata.LogRecord, pdata.Resource) { | ||
|
||
buffer := pdata.NewLogRecord() | ||
buffer.Body().SetStringVal("Example log") | ||
buffer.SetName("name") | ||
buffer.SetSeverityText("error") | ||
buffer.Attributes().Insert("attr1", pdata.NewAttributeValueString("1")) | ||
buffer.Attributes().Insert("attr2", pdata.NewAttributeValueString("2")) | ||
buffer.SetTraceID(pdata.NewTraceID([16]byte{1, 2, 3, 4})) | ||
buffer.SetSpanID(pdata.NewSpanID([8]byte{5, 6, 7, 8})) | ||
|
||
resource := pdata.NewResource() | ||
resource.Attributes().Insert("host.name", pdata.NewAttributeValueString("something")) | ||
|
||
return buffer, resource | ||
} | ||
|
||
func exampleJSON() string { | ||
jsonExample := `{"name":"name","body":"Example log","traceid":"01020304000000000000000000000000","spanid":"0506070800000000","severity":"error","attributes":{"attr1":"1","attr2":"2"},"resources":{"host.name":"something"}}` | ||
return jsonExample | ||
} | ||
|
||
func TestConvertString(t *testing.T) { | ||
in := exampleJSON() | ||
out, err := encodeJSON(exampleLog()) | ||
t.Log(in) | ||
t.Log(out, err) | ||
assert.Equal(t, in, out) | ||
} | ||
|
||
func TestConvertNonString(t *testing.T) { | ||
in := exampleJSON() | ||
log, resource := exampleLog() | ||
mapVal := pdata.NewAttributeValueMap() | ||
mapVal.MapVal().Insert("key1", pdata.NewAttributeValueString("value")) | ||
mapVal.MapVal().Insert("key2", pdata.NewAttributeValueString("value")) | ||
mapVal.CopyTo(log.Body()) | ||
|
||
out, err := encodeJSON(log, resource) | ||
t.Log(in) | ||
t.Log(out, err) | ||
assert.EqualError(t, err, "unsuported body type to serialize") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,6 +17,7 @@ package lokiexporter // import "github.com/open-telemetry/opentelemetry-collecto | |
import ( | ||
"bytes" | ||
"context" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"io/ioutil" | ||
|
@@ -30,23 +31,31 @@ import ( | |
"go.opentelemetry.io/collector/component" | ||
"go.opentelemetry.io/collector/consumer/consumererror" | ||
"go.opentelemetry.io/collector/model/pdata" | ||
"go.uber.org/multierr" | ||
"go.uber.org/zap" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/lokiexporter/internal/third_party/loki/logproto" | ||
) | ||
|
||
type lokiExporter struct { | ||
config *Config | ||
logger *zap.Logger | ||
client *http.Client | ||
wg sync.WaitGroup | ||
config *Config | ||
logger *zap.Logger | ||
client *http.Client | ||
wg sync.WaitGroup | ||
convert func(pdata.LogRecord, pdata.Resource) (*logproto.Entry, error) | ||
} | ||
|
||
func newExporter(config *Config, logger *zap.Logger) *lokiExporter { | ||
return &lokiExporter{ | ||
lokiexporter := &lokiExporter{ | ||
config: config, | ||
logger: logger, | ||
} | ||
if config.Format == "json" { | ||
lokiexporter.convert = convertLogToJSONEntry | ||
} else { | ||
lokiexporter.convert = convertLogBodyToEntry | ||
} | ||
return lokiexporter | ||
} | ||
|
||
func (l *lokiExporter) pushLogData(ctx context.Context, ld pdata.Logs) error { | ||
|
@@ -119,6 +128,8 @@ func (l *lokiExporter) stop(context.Context) (err error) { | |
} | ||
|
||
func (l *lokiExporter) logDataToLoki(ld pdata.Logs) (pr *logproto.PushRequest, numDroppedLogs int) { | ||
var errs error | ||
|
||
streams := make(map[string]*logproto.Stream) | ||
rls := ld.ResourceLogs() | ||
for i := 0; i < rls.Len(); i++ { | ||
|
@@ -135,7 +146,24 @@ func (l *lokiExporter) logDataToLoki(ld pdata.Logs) (pr *logproto.PushRequest, n | |
continue | ||
} | ||
labels := mergedLabels.String() | ||
entry := convertLogToLokiEntry(log) | ||
var entry *logproto.Entry | ||
var err error | ||
entry, err = l.convert(log, resource) | ||
if err != nil { | ||
// Couldn't convert so dropping log. | ||
numDroppedLogs++ | ||
errs = multierr.Append( | ||
errs, | ||
errors.New( | ||
fmt.Sprint( | ||
"failed to convert, dropping log", | ||
zap.String("format", l.config.Format), | ||
zap.Error(err), | ||
), | ||
), | ||
) | ||
continue | ||
} | ||
|
||
if stream, ok := streams[labels]; ok { | ||
stream.Entries = append(stream.Entries, *entry) | ||
|
@@ -150,6 +178,10 @@ func (l *lokiExporter) logDataToLoki(ld pdata.Logs) (pr *logproto.PushRequest, n | |
} | ||
} | ||
|
||
if errs != nil { | ||
l.logger.Error("some logs has been dropped", zap.Error(errs)) | ||
jpkrohling marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
pr = &logproto.PushRequest{ | ||
Streams: make([]logproto.Stream, len(streams)), | ||
} | ||
|
@@ -195,9 +227,20 @@ func (l *lokiExporter) convertAttributesToLabels(attributes pdata.AttributeMap, | |
return ls | ||
} | ||
|
||
func convertLogToLokiEntry(lr pdata.LogRecord) *logproto.Entry { | ||
func convertLogBodyToEntry(lr pdata.LogRecord, res pdata.Resource) (*logproto.Entry, error) { | ||
return &logproto.Entry{ | ||
Timestamp: time.Unix(0, int64(lr.Timestamp())), | ||
Line: lr.Body().StringVal(), | ||
}, nil | ||
} | ||
|
||
func convertLogToJSONEntry(lr pdata.LogRecord, res pdata.Resource) (*logproto.Entry, error) { | ||
line, err := encodeJSON(lr, res) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &logproto.Entry{ | ||
Timestamp: time.Unix(0, int64(lr.Timestamp())), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm curious about what is the behavior when the timestamp is bigger than the upper boundary for |
||
Line: line, | ||
}, nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you actually need this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, but was to be consistent with the previous exemple. We can remove it if you think it's better.
Does memory ballast shouldn't always be used when we receive pushed data like logs ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We recommend that people always use things like the batch processor and memory ballast, but I find it confusing to add something not relevant to what is being demonstrated.