log: support multiple outputs with independent formats #634
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.
Problem
log.WithOutput(...)+log.WithFormat(...)configure one formatter for one writer.A common production setup needs multiple destinations with independent formats:
Using
io.MultiWriter(os.Stdout, file)tees already-formatted bytes, so ANSI escapes leak into the file.Solution
Add a first-class multi-sink concept:
log.Output: pairs aWriterwith aFormat.log.WithOutputs(...): configures one or more outputs; each log entry is formatted and written to every output.This makes formatting a property of the destination, not of the global logger.
API
New
Backwards compatibility
This PR keeps the existing options:
log.WithOutput(w)mutates the first output writer.log.WithFormat(f)mutates the first output format.So existing code continues to compile and behave as before.
Examples
ANSI stdout + JSON file
Keep legacy single output configuration
Implementation notes
[]log.Output.Tests
WithOutput/WithFormatthrough the first-output behavior.TestMultipleOutputs)WithOutputsvalidation panicsdefaultOptions.Test plan
go test ./...