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: structured logging #9083

Merged
merged 13 commits into from
Oct 22, 2024
Merged

log: structured logging #9083

merged 13 commits into from
Oct 22, 2024

Conversation

ellemouton
Copy link
Collaborator

@ellemouton ellemouton commented Sep 10, 2024

Update LND logger(s) to make use of structured logging (the Logger interface now has structured logging messages (DebugS, InfoS etc))

See btclog update here: btcsuite/btclog#17

Tracing

The big bonus of this update is that you only need to add your identifier(s) once to the context when the request comes in and then as long as you pass that context through & use it when you log, you dont need to remember to specify the identifiers again. This can take the form of a request_id=?? for incoming user requests or channel_id=xyz for anything channel related.

Searchable logs

With the tracing above, each log will have a request_id=abcd in it and each log will use this same structure. So log searches will now become way easier.

The other thing is that the way we generally write logs today is using formatted strings like:

Out with the old

log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
		"waiting for channel open on-chain", pendingChanID[:],
		fundingPoint)

Which appears in the logs as:

[INF] FNDG: Finalizing pending_id(xyz) over ChannelPoint(abc), waiting for channel open on-chain"

This is not ideal for a few reasons:

  1. This log line is called from the funding manager but if a user initiated 2 fundings at the same time, then how do you know which one this log is referring to? The log author would need to remember to add some request identifier and then would need to remember to add that to each and every log within the funding manager so that it always shows up.
  2. When actually writing the log, you always need to go line up which param goes to which directive which makes it hard & bug-prone.
  3. If we want to go search through our logs (via grepping the log file or w/e) for how many times this exact log line occurred, it is actually really difficult because each directive (%d``%v) makes the log unique... And you cant necessarily just grep on Finalizing pending_id because what if there is another log line somewhere that starts the same way?
  4. Similarly to 3, if we want to go find where in the code base a log is being emitted from, this can be tricky if there are many directives to work around.

Enter structured logging:

In with the new

The above log line could now be converted into something like this:

log.InfoS(ctx, "Finalizing channel ID. Waiting for channel open on-chain",
		btclog.Hex("pending_id", pendingChanID[:]),
		"channel_point", fundingPoint.String())

Which will result in the following log line:

[INF] FNDG: Finalizing channel ID. Waiting for channel open on-chain request_id=123 pending_id=xyz channel_point=abc

A few things to note:

  • it takes a context from which it may extract other key-value pairs (such as request_id) at log time.
  • The log message is a constant. This makes it easy to search both the logs and the code base for this log line.
  • All variables with in the log are now key value pairs. This makes constructing the log line easy to do.
  • You as the dev dont need to remember to go add the request_id each time you add a new log line! It will just automagically appear 🪄

Details

  • This new implementation is flexible enough to allow callers to pass in their own slog.Handlers (which underneath could be a json formatter, a logfmt formatter or any anything else like a charm Handler

Usage

The idea is that the msg passed to an S method should be a constant. The attr... params are then used for key-value pairs.

log.InfoS(ctx, "User performed a request",
			"user_id", id,
			"request_uri: ", uri)

Each new method also takes a context.Context. The WithCtx helper can be used to attach any key-value pairs to a
context and then when the logger is called, the pairs will be extracted from the context and added as attributes in the log.

For example:

ctx := WithCtx(context.Background(), "user_id", id)

// This log will include both the `user_id` and `request_uri` attributes.
log.InfoS(ctx, "User performed a request", "request_uri", uri)

Other additions:

Config options

  • This also introduces a new --logging.console.disable option to disable logs being written
    to stdout and a new --logging.file.disable option to disable writing logs to the standard log file.

  • It also has --logging.console.no-timestamps & --logging.file.no-timestamps to omit timestamps from the logs

  • It also adds new --logging.console.call-site and --logging.console.call-site options which can be used to include log line source call-site in the log lines. The options are "off", "short" (source file name and line number) and "long" (full path to source file and line number)

  • finally, there is a new --logging.console.style option which can be set to use color formatting - this is only available if the dev build flag is set.

TODO:

  • update docs with guidelines for using structured logging methods

Fixes #8713
Fixes #6828
Fixes #6163

Copy link
Contributor

coderabbitai bot commented Sep 10, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

🏷️ Labels to auto review (1)
  • llm-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ellemouton ellemouton changed the title https://github.com/btcsuite/btclog/pull/17 log: structured logging Sep 10, 2024
@guggero guggero self-requested a review September 10, 2024 18:38
@ellemouton ellemouton force-pushed the slog branch 2 times, most recently from 61e241c to 9ca6dac Compare September 10, 2024 19:13
@ellemouton ellemouton added the logging Related to the logging / debug output functionality label Sep 10, 2024
@ellemouton ellemouton force-pushed the slog branch 2 times, most recently from 3bdef45 to 4a09edb Compare September 11, 2024 06:28
@ellemouton ellemouton force-pushed the slog branch 3 times, most recently from f259e66 to 9587f54 Compare September 11, 2024 07:40
@ellemouton ellemouton self-assigned this Sep 11, 2024
@ellemouton ellemouton force-pushed the slog branch 2 times, most recently from 81f301e to fb0489c Compare September 11, 2024 09:42
@saubyk saubyk added this to the v0.19.0 milestone Sep 11, 2024
@saubyk saubyk requested a review from ziggie1984 September 12, 2024 15:07
@ellemouton ellemouton force-pushed the slog branch 2 times, most recently from 845fa01 to cde7702 Compare September 12, 2024 15:30
@ellemouton ellemouton force-pushed the slog branch 5 times, most recently from 5ce706e to 03c2689 Compare September 16, 2024 06:24
@ellemouton
Copy link
Collaborator Author

ellemouton commented Oct 15, 2024

added a bonus commit which adds call-site to the log lines (if user wants) :)

Screenshot 2024-10-15 at 18 29 14

Nice for devs so they can click through to the log :)

@@ -98,13 +111,55 @@ func (p *PrefixLog) Critical(v ...interface{}) {
p.log.Critical(p.addArgsPrefix(v)...)
}

// TraceS writes a structured log with the given message and key-value pair
// attributes with LevelTrace to the log.
func (p *PrefixLog) TraceS(ctx context.Context, msg string, attrs ...any) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we create the context inside this method so the caller doesn't need to create it? Think this way we won't need more code lines when creating logs

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Passing in a context is part of what's cool about this feature cause we can add kv pair attributes to a context and that will get logged without us needing to remember to include it in the log every time

@ellemouton ellemouton force-pushed the slog branch 3 times, most recently from 7dd1b56 to 0dbd683 Compare October 17, 2024 19:12
Copy link
Collaborator

@guggero guggero left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK, LGTM 🎉

This is sooo nice 🤩

build/logrotator.go Outdated Show resolved Hide resolved
build/config_dev.go Outdated Show resolved Hide resolved
build/log_shutdown.go Outdated Show resolved Hide resolved
build/config.go Show resolved Hide resolved
build/config_dev.go Outdated Show resolved Hide resolved
Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great PR 👏, a bit complex to grasp because of all the interface but makes it really flexible as well. Can't wait until we actually use the new power of SLogs.

build/handler_sets.go Show resolved Hide resolved
log.go Show resolved Hide resolved
"github.com/btcsuite/btclog/v2"
)

// NewDefaultLoggers returns the standard console logger and rotating log
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this name a bit misleading, because it returns a handler not a logger or was it intentional. Moreover I think we separated the rotating log from the logger so this comment seems to be outdated ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed the name.

Moreover I think we separated the rotating log from the logger so this comment seems to be outdated ?

looks correct to me? it returns a console log handler and a rotator file handler

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Upps, you are right sorry

build/logrotator.go Show resolved Hide resolved
build/handler_sets.go Show resolved Hide resolved
sample-lnd.conf Show resolved Hide resolved
build/config_dev.go Show resolved Hide resolved
build/config_dev.go Outdated Show resolved Hide resolved
To make the upcoming commits easier to review and for general code
organisation.
These are two separate concerns. So this commit splits them up and just
passes a LogWriter from the one to the other. This will become cleaner
in an upcoming commit where the Rotator will implement io.Writer and
there will no longer be a need for LogWriter.
This commit then also adds an implementation of the btclog.Handler
interface called `handlerSets` which basically lets us have a Handler
backed by many Handlers (we need one for the stdout and one for our log
file).
@ellemouton
Copy link
Collaborator Author

Thanks @ziggie1984 - PTAL 🙏

@ellemouton ellemouton requested a review from ziggie1984 October 22, 2024 13:41
Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick reply, LGTM

build/config.go Show resolved Hide resolved
build/config_dev.go Show resolved Hide resolved
Start using the new slog handlers. With this commit we also remove the
need for the LogWriter since we let our LogRotator implement io.Writer
and pass that in to our log file handler.
This commit adds config options so that users can for both the console
logger and the file logger set the following things:

- disable the logger
- omit timestamps from log lines.
Since most of our projects will use the same handler duo and apply the
config options the same way, let's make our lives easier and add a
default handler constructor.
This will only be available when the dev build tag is set
Such that it implements the new expanded interface of btclog v2.
Ensure that the ShutdownLogger correctly calls shutdown for the new
CriticalS method added to the btclog.Logger.
@ellemouton ellemouton merged commit b4ef22b into lightningnetwork:master Oct 22, 2024
29 of 34 checks passed
@ellemouton ellemouton deleted the slog branch October 22, 2024 18:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
logging Related to the logging / debug output functionality
Projects
Status: Done
6 participants