Skip to content
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

Receive all logs if no attributes are specified #37721

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/receive-all-cloudflare.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: cloudflarereceiver

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Ingest all attributes by default when attributes map is empty

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [37720]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
16 changes: 16 additions & 0 deletions receiver/cloudflarereceiver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ If the receiver will be handling TLS termination:
- This receiver was built with the Cloudflare `http_requests` dataset in mind, but should be able to support any Cloudflare dataset. If using another dataset, you will need to set the `timestamp_field` appropriately in order to have the log record be associated with the correct timestamp. the timestamp must be formatted RFC3339, as stated in the Getting Started section.
- `attributes`
- This parameter allows the receiver to be configured to set log record attributes based on fields found in the log message. The fields are not removed from the log message when set in this way. Only string, boolean, integer or float fields can be mapped using this parameter.
- When the `attributes` configuration is empty, the receiver will automatically ingest all fields from the log messages as attributes, using the original field names as attribute names.


### Example:
Expand All @@ -66,3 +67,18 @@ receivers:
ClientIP: http_request.client_ip
ClientRequestURI: http_request.uri
```

### Example with automatic attribute ingestion:
```yaml
receivers:
cloudflare:
logs:
tls:
key_file: some_key_file
cert_file: some_cert_file
endpoint: 0.0.0.0:12345
secret: 1234567890abcdef1234567890abcdef
timestamp_field: EdgeStartTimestamp
attributes:
# Specifying no attributes ingests them all
```
43 changes: 28 additions & 15 deletions receiver/cloudflarereceiver/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,23 +272,36 @@ func (l *logsReceiver) processLogs(now pcommon.Timestamp, logs []map[string]any)
}

attrs := logRecord.Attributes()
for field, attribute := range l.cfg.Attributes {
if v, ok := log[field]; ok {
switch v := v.(type) {
case string:
attrs.PutStr(attribute, v)
case int:
attrs.PutInt(attribute, int64(v))
case int64:
attrs.PutInt(attribute, v)
case float64:
attrs.PutDouble(attribute, v)
case bool:
attrs.PutBool(attribute, v)
default:
l.logger.Warn("unable to translate field to attribute, unsupported type", zap.String("field", field), zap.Any("value", v), zap.String("type", fmt.Sprintf("%T", v)))
for field, v := range log {
attrName := field
if len(l.cfg.Attributes) != 0 {
// Only process fields that are in the config mapping
if mappedAttr, ok := l.cfg.Attributes[field]; ok {
attrName = mappedAttr
} else {
// Skip fields not in mapping when we have a config
continue
}
}
// else if l.cfg.Attributes is empty, default to processing all fields with no renaming

switch v := v.(type) {
case string:
attrs.PutStr(attrName, v)
case int:
attrs.PutInt(attrName, int64(v))
case int64:
attrs.PutInt(attrName, v)
case float64:
attrs.PutDouble(attrName, v)
case bool:
attrs.PutBool(attrName, v)
default:
l.logger.Warn("unable to translate field to attribute, unsupported type",
zap.String("field", field),
zap.Any("value", v),
zap.String("type", fmt.Sprintf("%T", v)))
}
}

err := logRecord.Body().SetEmptyMap().FromRaw(log)
Expand Down
84 changes: 84 additions & 0 deletions receiver/cloudflarereceiver/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,90 @@ func TestHandleRequest(t *testing.T) {
}
}

func TestEmptyAttributes(t *testing.T) {
now := time.Time{}

testCases := []struct {
name string
payload string
attributes map[string]string
}{
{
name: "Empty Attributes Map",
payload: `{ "ClientIP": "89.163.253.200", "ClientRequestHost": "www.theburritobot0.com", "ClientRequestMethod": "GET", "ClientRequestURI": "/static/img/testimonial-hipster.png", "EdgeEndTimestamp": "2023-03-03T05:30:05Z", "EdgeResponseBytes": "69045", "EdgeResponseStatus": "200", "EdgeStartTimestamp": "2023-03-03T05:29:05Z", "RayID": "3a6050bcbe121a87" }
{ "ClientIP" : "89.163.253.201", "ClientRequestHost": "www.theburritobot1.com", "ClientRequestMethod": "GET", "ClientRequestURI": "/static/img/testimonial-hipster.png", "EdgeEndTimestamp": "2023-03-03T05:30:05Z", "EdgeResponseBytes": "69045", "EdgeResponseStatus": "200", "EdgeStartTimestamp": "2023-03-03T05:29:05Z", "RayID": "3a6050bcbe121a87" }`,
attributes: map[string]string{},
},
{
name: "nil Attributes",
payload: `{ "ClientIP": "89.163.253.200", "ClientRequestHost": "www.theburritobot0.com", "ClientRequestMethod": "GET", "ClientRequestURI": "/static/img/testimonial-hipster.png", "EdgeEndTimestamp": "2023-03-03T05:30:05Z", "EdgeResponseBytes": "69045", "EdgeResponseStatus": "200", "EdgeStartTimestamp": "2023-03-03T05:29:05Z", "RayID": "3a6050bcbe121a87" }
{ "ClientIP" : "89.163.253.201", "ClientRequestHost": "www.theburritobot1.com", "ClientRequestMethod": "GET", "ClientRequestURI": "/static/img/testimonial-hipster.png", "EdgeEndTimestamp": "2023-03-03T05:30:05Z", "EdgeResponseBytes": "69045", "EdgeResponseStatus": "200", "EdgeStartTimestamp": "2023-03-03T05:29:05Z", "RayID": "3a6050bcbe121a87" }`,
attributes: nil,
},
}

expectedLogs := func(t *testing.T, payload string) plog.Logs {
logs := plog.NewLogs()
rl := logs.ResourceLogs().AppendEmpty()
sl := rl.ScopeLogs().AppendEmpty()
sl.Scope().SetName("github.com/open-telemetry/opentelemetry-collector-contrib/receiver/cloudflarereceiver")

for idx, line := range strings.Split(payload, "\n") {
lr := sl.LogRecords().AppendEmpty()

require.NoError(t, lr.Attributes().FromRaw(map[string]any{
"ClientIP": fmt.Sprintf("89.163.253.%d", 200+idx),
"ClientRequestHost": fmt.Sprintf("www.theburritobot%d.com", idx),
"ClientRequestMethod": "GET",
"ClientRequestURI": "/static/img/testimonial-hipster.png",
"EdgeEndTimestamp": "2023-03-03T05:30:05Z",
"EdgeResponseBytes": "69045",
"EdgeResponseStatus": "200",
"EdgeStartTimestamp": "2023-03-03T05:29:05Z",
"RayID": "3a6050bcbe121a87",
}))

lr.SetObservedTimestamp(pcommon.NewTimestampFromTime(now))
ts, err := time.Parse(time.RFC3339, "2023-03-03T05:29:05Z")
require.NoError(t, err)
lr.SetTimestamp(pcommon.NewTimestampFromTime(ts))
lr.SetSeverityNumber(plog.SeverityNumberInfo)
lr.SetSeverityText(plog.SeverityNumberInfo.String())

var log map[string]any
err = json.Unmarshal([]byte(line), &log)
require.NoError(t, err)

payloadToExpectedBody(t, line, lr)
}

return logs
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
recv := newReceiver(t, &Config{
Logs: LogsConfig{
Endpoint: "localhost:0",
TLS: &configtls.ServerConfig{},
TimestampField: "EdgeStartTimestamp",
Attributes: tc.attributes,
},
},
&consumertest.LogsSink{},
)
var logs plog.Logs
rawLogs, err := parsePayload([]byte(tc.payload))
if err == nil {
logs = recv.processLogs(pcommon.NewTimestampFromTime(time.Now()), rawLogs)
}
require.NoError(t, err)
require.NotNil(t, logs)
require.NoError(t, plogtest.CompareLogs(expectedLogs(t, tc.payload), logs, plogtest.IgnoreObservedTimestamp()))
})
}
}

func gzippedMessage(message string) string {
var b bytes.Buffer
w := gzip.NewWriter(&b)
Expand Down
Loading