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

Log contents of interface objects #360

Merged
merged 1 commit into from
Mar 6, 2023
Merged

Log contents of interface objects #360

merged 1 commit into from
Mar 6, 2023

Conversation

uablrek
Copy link
Contributor

@uablrek uablrek commented Feb 7, 2023

Description

Log contents of interface objects instead of the object itself in structured logging.

After a bit of fumbling I realized the right way is to define a custom MarshalJSON function for the real class. Example:

func (t *Target) MarshalJSON() ([]byte, error) {
	ts := struct {
		Identifier int      `json:"identifier"`
		IPs        []string `json:"ips"`
	}{
		t.getIdentifier(),
		t.nspTarget.GetIps(),
	}
	return json.Marshal(&ts)
}

Issue link

#358

Checklist

  • Purpose
    • Bug fix
    • New functionality
    • Documentation
    • Refactoring
    • CI
  • Test
    • Unit test
    • E2E Test
    • Tested manually
  • Introduce a breaking change
    • Yes (description required)
    • No
  • Introduce changes in the Operator
    • Yes (description required)
    • No

@uablrek
Copy link
Contributor Author

uablrek commented Feb 7, 2023

More to come. I will squash commits before "Ready for review". It wasn't nearly as bad as I feared.

@uablrek uablrek added the kind/bug Something isn't working label Feb 7, 2023
@uablrek uablrek force-pushed the uablrek-logging-2 branch 2 times, most recently from 3b129ed to 8f9bc26 Compare February 7, 2023 12:10
@uablrek uablrek marked this pull request as ready for review March 6, 2023 12:37
@uablrek uablrek merged commit 8bd94c2 into master Mar 6, 2023
@uablrek
Copy link
Contributor Author

uablrek commented Feb 26, 2024

It turns out that this isn't the way after all.

All implementations of an interface that wants to use structured logging should implement the logr.Marshaler interface. It should not be part of the interface itself, but the real implementation types should define a MarshalLog() function. Example (not tested):

func (t *Target) MarshalLog() any {
	ts := struct {
		Identifier int      `json:"identifier"`
		IPs        []string `json:"ips"`
	}{
		t.getIdentifier(),
		t.nspTarget.GetIps(),
	}
	return &ts
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants