logctxr

package module
v0.0.0-...-e25837e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2020 License: Unlicense Imports: 2 Imported by: 0

README

logctxr

logctxr is a helper package for the logr minimal logging API that enables a Logger instance to be embedded in and retrieved from a Go context.

Since the core of a program only needs to import github.com/iand/logctxr it reduces the dependency on a specific logger implementation. Typically a program will create a root logger at startup and embed it into a context that is passed through the rest of the program. Submodules of the program can derive new loggers using the standard logr interface.

Example usage:

package main

import (
    "github.com/iand/logctxr"
    "github.com/iand/logfmtr"
)


func init() {
    // Ensure that logctxr knows how to make new logger instances
    // if it needs to
    logctxr.NewLogger = logfmtr.New
}

func main() {
    // Create a root logger
    root := logfmtr.New().WithName("root").V(2)

    // Embed the logger in a context
    loggerCtx := logctxr.NewContext(context.Background(), root)

    // Pass the context to the other function
    other(loggerCtx)

}


// A function that uses a context
func other(ctx context.Context) {
    // Retrieve the logger from the context
    logger := logctxr.FromContext(ctx)
    logger.Info("the sun is shining")
}

Author

License

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. For more information, see http://unlicense.org/ or the accompanying UNLICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NewLogger func() logr.Logger = func() logr.Logger {
	panic("NewLogger must be set to a function that can create new logger instances")
}

NewLogger returns a new instance of a Logger. This variable should be set to a function that returns an implementation of Logger before using FromContext.

Functions

func FromContext

func FromContext(ctx context.Context) logr.Logger

FromContext returns a logr.Logger constructed from the context or calls NewLogger if no logger details are found in the context.

func NewContext

func NewContext(ctx context.Context, l logr.Logger) context.Context

NewContext returns a new context that embeds the logger.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL