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/slog: structured, leveled logging #56345
Comments
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This is a huge API surface without any real production testing (AIUI). Perhaps it might be better to land it under golang.org/x for some time? Eg, like context, xerrors changes. |
It's available under golang.org/x/exp/slog |
This comment has been hidden.
This comment has been hidden.
I love most of what this does, but I don't support its addition as it stands. Specifically, I have issues with the option to use inline key-value pairs in the log calls. I believe the attributes system alone is fine. Logging does not need the breakage that key-value args like that allow. The complexity in the documentation around Log should be a warning sign.
The suggestion was that potential problems with key-value misalignment will all be solved by vet checks. As I mentioned in this thread of the discussion, relying on vet should be viewed a warning as to potential problems with the design, not a part of the design itself. Vet should not be a catch-all, and we should do what we can to avoid requiring vet warnings to safely develop go. An accidentally deleted/missed or added/extra argument in key value logging would offset the keys and values after it. That could easily bog down a logging system trying to index all the new "keys" it is getting. It could also lead to data being exposed in a way that it should not be. I acknowledge that neither of these examples are all that likely in a well defined system, or somewhere with good practices around code reviewing etc.. But they are possible. |
@deefdragon Doesn't this concern apply to Printf as well? Is the difference the dependency on these logs by external systems..? |
Based on that the Go standard library is very often being recommended as source of idiomatic code, and this package aspires to be merged as part of it, I would like you explain to me the involvement of context package. If some object uses logger, isn't it its dependency? Shouldn't we make the dependencies explicit? Isn't this logger smuggling bad practice? If passing the logger by context is idiomatic, is *sql.DB too? Why has the logger stored context? It violates the most famous sentence from the documentation for context
Logger in context containing its own context inside ... Frankly, I'm a bit confused. |
@hherman1 The same concern does apply to printf, tho it's not as bad compared to logging. With printf, most statements are consumed as a single chunk, and only consumed locally by the programmer. Being misaligned is easy enough for a human to notice, parse, and correct. In the case of Sprintf, where it might not be consumed by the programmer, and instead be used as an argument to something, the "testing" during development that is making sure the program starts would likely catch most misalignment. Being off by one in a log is much harder to catch as it has no real impact in the program's execution. You only notice there is an issue when you have to go through your logs. |
I think I share some of @prochac 's concerns regarding context. Maybe I'm being a bit of a luddite, but recommending that the logger is passed around inside context rather than via explicit dependency injection, smells a bit funny to me. Context, from what I have always followed, is for request-scoped information, rather than dependencies. And the more clarity surfacing dependencies the better. IE just assuming the right logger is in context, and getting the default one because it's still getting some logger |
I think there are two approaches here:
I've used both patterns frequently in high-scale production services; and both have their places. I'd definitely like to see slog promote context-propagated logging as the observability benefits are huge. |
Appreciate your explanation @v3n . I'm still having a slightly hard time understanding the benefit of the logger itself being passed around in context. I understand propagating the log correlation information via context, and we currently use the otelzap implementation that does this sort of thing via ErrorContext(ctx, ...) etc logging methods. I like the WithContext methods proposed here, passing the context to the logger, in similar fashion. It's more the logger itself being passed around inside the context that feels a bit odd to me The zap and otelzap libraries do allow for the same kind of thing, whereby you can get the logger from context etc (and I'm sure others do), it's just this being in the std library it's more of a recommendation for this kind of pattern |
I still want a standard handler for |
@deefdragon, we'll have a vet check for that. |
@seankhliao, such a handler seems easy to write, and it's not clear to me yet whether there is enough demand to include it. Let's hold off for now; we can always add it later. |
@prochac, that is a design principle, not a hard-and-fast rule. It is there to steer people away from buggy code, but that has to be weighed against other factors. In this case, we knew that passing tracing information to logging was an important feature, but we didn't want to add a context argument to every log output method. This was our solution. |
@mminklet, scoping a logger to a request is a common pattern, and is probably the main application of the ability to add a Logger to a context. It doesn't preclude dependency injection; if that works for you, stick with it. |
This is a significant proposal. @jba can you do a video talk on this. And, perhaps, a blog post? |
@jba As I said in my original post, I don't think that's a good solution.
|
I like this in general. One API nit from an experiment in s3-upload-proxy: it would be good to have a way to convert a string into to the level (say you want to allow users set an environment variable like LOG_LEVEL=debug and have that translated to Other libraries (logrus, zerolog, zap) call that function |
|
The additional '+'/'-' terms put a twist on this, I think it'd be nice to have. (I had this laying around: https://go.dev/play/p/Izwzgd8Kmc9) |
Three comments on the proposal: One thing which irritated me with zap was the existence of both sugared and attribute log methods. My second observation is that we have 10 Attr constructors, one for each common type we want to log, + any. Finally, I think it is very good (but perhaps overdue) that we are moving towards a canonical production strength logging library in stdlib. Most libraries need some level of logging, if only for debugging. And not having a standard interface of |
I disagree. There is only one
The answer is, "hopefully." With the current implementation, you can only reduce the API surface at a considerable time penalty. But that may change before this API is frozen. See this item in the discussion.
According to my analysis, |
This proposal has been added to the active column of the proposals project |
I'm with @prochac and @mminklet in that passing logger in context seems awkward. However, I see your point about context propagation and @v3n point:
But then @jba (apologies if this was already discussed in #54763, I tried to & failed to find it there) did you consider something like context-propagated log-context, as opposed to propagating the whole logger? I frequently wish I could do easily is adding log-context to an already existing logger, like: logger = slow.WithContext(ctx).With("method", r.Method ...)
.....
err := doSomething(c ctx) err {
doSomethingElse(c ctx) {
somethingVeryDeep(c ctx) {
// do some other work
slog.AddToContext(ctx, "workResult", ok)
}
somethingVeryDeepAgain(c ctx) {
// do some work
slog.AddToContext(ctx, "otherWorkResult", ok)
}
} ()
} ()
if err != nil {
logger.Error("requestFailed") // `slog` extract values for me.
} This would allow me to log once per request/error instead of tens of scattered log-lines which I then need to correlate with request/span ids. I think this could also support https://go-review.googlesource.com/c/proposal/+/444415/5/design/56345-structured-logging.md#754 ctx, span := tracer.Start(ctx, name, opts) since
|
There may be a hint of namespace clobbring in ReplaceAttr, where matching on a key string is invoked before group prefixes are applied (example: https://go.dev/play/p/yFNXLz3gklD). I think it's a reasonable behavior; the version of A version of |
Change https://go.dev/cl/478355 mentions this issue: |
@jba hey, I was wondering if you saw my message above, #56345 (comment) , on including an error field in Record? |
Bench log file is created non-portably, only works on system where "/tmp" existed and "/" is path separator. Fixing this by using portable methods from std lib. Updates #56345 Change-Id: I1f6b6b97b913ca56a6053beca7025652618ecbf3 Reviewed-on: https://go-review.googlesource.com/c/go/+/478355 Run-TryBot: Ian Lance Taylor <iant@google.com> Reviewed-by: Ian Lance Taylor <iant@google.com> Auto-Submit: Ian Lance Taylor <iant@google.com> Reviewed-by: Jonathan Amsterdam <jba@google.com> Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com> TryBot-Result: Gopher Robot <gobot@golang.org>
Delete the set of bytes that need quoting in TextHandler, because it is almost identical to the set for JSON. Use JSONHandler's safeSet with a few exceptions. Updates #56345. Change-Id: Iff6d309c067affef2e5ecfcebd6e1bb8f00f95b9 Reviewed-on: https://go-review.googlesource.com/c/go/+/478198 Reviewed-by: Ian Lance Taylor <iant@google.com> Run-TryBot: Jonathan Amsterdam <jba@google.com> TryBot-Result: Gopher Robot <gobot@golang.org>
@veqryn, I did read it but forgot to respond. The consensus on this issue were that errors shouldn't have any special status: in terms of common key name, deduplication, and so on, they present the same problems as any other attribute. So we decided against treating them specially. That would include an error field on Record. |
In that case, can we bring back Also, I do wish to say that the current Record fields of Time, Message, and Level, could all be treated as regular attributes too. But they aren't, for good reason, and I think those reasons extend to the Error field. I think the decision to treat errors as a regular attribute should be reconsidered. |
Structured logging establishes rules about the structure of log events, basically that they are key=val pairs, and about the types of those keys and vals. It should have no concept of semantics of any key or val, like if it is an error or a status code or a referer address or anything else like that. Those concepts exist at a higher level of abstraction. |
Then let there be an Error field on Record, and the handlers and higher levels can deal with it appropriately. The fact that we are even considering a structured logger, instead of continuing with the existing builtin log package, shows that we have some practical considerations for how we and our libraries log and how we consume, view, and search those logs. Otherwise we could just say that the existing log.Println function is fine and everything else is just a higher level of abstraction. Please explain to me why Record has fields for Time, Level, and Message, but doesn't have one for Error? They could easily be made into attributes, but then people would use different keys for them, and everyone would have to write custom handlers... Errors are just as central to a log record/entry as the time, level, and message. Errors are we why we are even logging anything at all to begin with, rather than just using metrics. Error values are central to the golang language. We need a better solution than just ignoring this until after the interface is set and claiming the resulting problems are for the users to fix. |
I agree with you that a structured logging package should not define a time, level, or message key, either. |
An error can be a complex value. It doesn't make sense to me to squash that into a plain string before a backend Handler handles it. Handlers can handle Attrs with error values however they want to, including the uniform way you have in mind. Use your own ErrorsHaveSameKeyHandler if you like. That approach has problems that were discussed above.
I and others have argued for removing Level and Message too. I haven't seen the Go Team articulate the rationale for having them, beyond trying to mimic logr. We're stuck with them, it seems. |
Who said anything about strings?
I can't wait for dealing with logs that look like this, because every library is using a different key string:
That will not be fun to deal with when I search in elastic search or scalyr. Or when I setup alerting rules or dashboard based on logs. Yet this is what we will get if we don't make separate fields for Time, Level, Message, and Error. |
I think there were reasonable points about the uniformity of the API, but I don’t think the difference between error, time, and message have been addressed. I don’t feel convinced that removing error support was the right decision. |
@veqryn in your example you use level warn with an error. It can also be the opposite, an error level without a Go error. |
The utopia of everyone using the same keys in their logs from all software will not happen even if The log15 package for Go was first published nearly nine years ago on May 19, 2014. If we look at log15's abstractions it has a Logger, a Record, a Handler, and a Formatter. We haven't come that far from that design in The log15 Record type is declared as:
The Many times the keys we have to use in our logs are dictated by forces outside of our code, programming language, or team. See also #56345 (comment) in which I said:
But read the whole comment (if the Github UI lets you) because I believe it makes good points beyond what I've said in this post. |
@ChrisHines why do you feel ok about having built-in message and time fields but not a built in error field? |
I don't really. I argued against that a while back too. There is a semantic difference with those attributes in Note that the logging package I am most well known for, My biggest regret with the go-kit/log design is leaving levels out of the core package because that caused much design difficulty to layer on later and I think the result is sub-optimal in a few ways.
|
The great thing about having Time, Level, Message, and Error on the Record struct is that then the handler would determine what the keys are, which means it is in my control, and outside of the control of a library or sub-dependency that I am using. |
Today I just upgraded slog on our current project, I had to change all the
It's fine that the current slog proposal permit this. Maybe we could start an other proposal to discuss if conventional is not enough and an ErrorAttr could be included or something like that ? |
What you're describing here is more like semantic logging than structured logging. |
? I think you might be splitting hairs on concepts and theory here. What I described is literally how slog works right now, with the exception that the Error field is not yet a part of a Record. |
FWIW I think you could make the argument that error should be excluded and message/time included because error is less valuable to users than message & time is. I would be interested to see that argument though if that is the position of the go team. |
@jba Have you considered making |
When
Per Dan Cliff in Gophers Slack, we can make a passable GCP StackDriver format If we want the Function name, the Not sure if the Function name is a commonly desired requirement, but I thought I would point it out. |
Give an example illustrating the problem with dots inside groups or keys. Clarify that to fix it in general, you need to do more than escape the keys, since that won't distinguish the group "a.b" from the two groups "a" and "b". Updates #56345. Change-Id: Ide301899c548d50b0a1f18e93e93d6e11ad485cf Reviewed-on: https://go-review.googlesource.com/c/go/+/478199 Reviewed-by: Alan Donovan <adonovan@google.com> Run-TryBot: Jonathan Amsterdam <jba@google.com> TryBot-Result: Gopher Robot <gobot@golang.org>
I would disagree. Neither |
Add a suite of benchmarks for the LogAttrs method, which is intended to be fast. Updates #56345. Change-Id: If43f9f250bd588247c539bed87f81be7f5428c6d Reviewed-on: https://go-review.googlesource.com/c/go/+/478200 TryBot-Result: Gopher Robot <gobot@golang.org> Run-TryBot: Jonathan Amsterdam <jba@google.com> Reviewed-by: Alan Donovan <adonovan@google.com>
That is my point. The two types don't export anything but the -func NewJSONHandler(w io.Writer) *JSONHandler
-func NewTextHandler(w io.Writer) *TextHandler
-func (opts HandlerOptions) NewJSONHandler(w io.Writer) *JSONHandler
-func (opts HandlerOptions) NewTextHandler(w io.Writer) *TextHandler
+func NewJSONHandler(w io.Writer) Handler
+func NewTextHandler(w io.Writer) Handler
+func (opts HandlerOptions) NewJSONHandler(w io.Writer) Handler
+func (opts HandlerOptions) NewTextHandler(w io.Writer) Handler This would be similar to the std |
@lmittmann In general, I'd recommend returning exported types, instead of opaque interfaces. That is because it enables you to later add type-specific methods where appropriate without breaking compatibility. For example, the Note that |
We propose a new package providing structured logging with levels. Structured logging adds key-value pairs to a human-readable output message to enable fast, accurate processing of large amounts of log data.
See the design doc for details.
The text was updated successfully, but these errors were encountered: