log

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2024 License: MIT Imports: 7 Imported by: 16

README

Log Module

ci go report codecov Deps PkgGoDev

Logging module based on Zerolog.

Installation

go get github.com/ankorstore/yokai/log

Documentation

This module provides a Logger, offering all Zerolog methods.

Usage

To create a Logger:

package main

import (
	"os"

	"github.com/ankorstore/yokai/log"
	"github.com/rs/zerolog"
)

var logger, _ = log.NewDefaultLoggerFactory().Create()

// equivalent to:
var logger, _ = log.NewDefaultLoggerFactory().Create(
	log.WithServiceName("default"),   // adds {"service":"default"} to log records
	log.WithLevel(zerolog.InfoLevel), // logs records with level >= info
	log.WithOutputWriter(os.Stdout),  // sends logs records to stdout
)

To use the Logger:

package main

import (
	"github.com/ankorstore/yokai/log"
)

func main() {
	logger, _ := log.NewDefaultLoggerFactory().Create()

	logger.Info().Msg("some message") // {"level:"info", "service":"default", "message":"some message"}
}

See Zerolog documentation for more details about available methods.

Context

This module provides the log.CtxLogger() function that allow to extract the logger from a context.Context.

If no logger is found in context, a default Zerolog based logger will be used.

Testing

This module provides a TestLogBuffer, recording log records to be able to assert on them after logging:

package main

import (
	"fmt"

	"github.com/ankorstore/yokai/log"
	"github.com/ankorstore/yokai/log/logtest"
)

func main() {
	buffer := logtest.NewDefaultTestLogBuffer()

	logger, _ := log.NewDefaultLoggerFactory().Create(log.WithOutputWriter(buffer))

	logger.Info().Msg("some message example")

	// test on attributes exact matching
	hasRecord, _ := buffer.HasRecord(map[string]interface{}{
		"level":   "info",
		"message": "some message example",
	})

	fmt.Printf("has record: %v", hasRecord) // has record: true

	// test on attributes partial matching
	containRecord, _ := buffer.ContainRecord(map[string]interface{}{
		"level":   "info",
		"message": "message",
	})

	fmt.Printf("contain record: %v", containRecord) // contain record: true
}

You can also use the provided test assertion helpers in your tests:

  • AssertHasLogRecord: to assert on exact attributes match
  • AssertHasNotLogRecord: to assert on exact attributes non match
  • AssertContainLogRecord: to assert on partial attributes match
  • AssertContainNotLogRecord: to assert on partial attributes non match

and use Dump() to print the current content of the TestLogBuffer.

For example:

package main_test

import (
	"fmt"
	"testing"

	"github.com/ankorstore/yokai/log"
	"github.com/ankorstore/yokai/log/logtest"
)

func TestLogger(t *testing.T) {
	buffer := logtest.NewDefaultTestLogBuffer()
	
	logger, _ := log.NewDefaultLoggerFactory().Create(log.WithOutputWriter(buffer))

	logger.Info().Msg("some message example")

	// print records
	buffer.Dump()
	
	// assertion success
	logtest.AssertHasLogRecord(t, buffer, map[string]interface{}{
		"level":   "info",
		"message": "some message example",
	})

	// assertion success
	logtest.AssertHasNotLogRecord(t, buffer, map[string]interface{}{
		"level":   "info",
		"message": "some invalid example",
	})

	// assertion success
	logtest.AssertContainLogRecord(t, buffer, map[string]interface{}{
		"level":   "info",
		"message": "message",
	})

	// assertion success
	logtest.AssertContainNotLogRecord(t, buffer, map[string]interface{}{
		"level":   "info",
		"message": "invalid",
	})
}

Documentation

Index

Constants

View Source
const (
	Level   = "level"
	Message = "message"
	Service = "service"
	Time    = "time"
	Stdout  = "stdout"
	Noop    = "noop"
	Test    = "test"
	Console = "console"
)

Variables

This section is empty.

Functions

func FetchLogLevel

func FetchLogLevel(level string) zerolog.Level

FetchLogLevel returns a Zerolog level for a given value.

Types

type DefaultLoggerFactory

type DefaultLoggerFactory struct{}

DefaultLoggerFactory is the default LoggerFactory implementation.

func (*DefaultLoggerFactory) Create

func (f *DefaultLoggerFactory) Create(options ...LoggerOption) (*Logger, error)

Create returns a new Logger, and accepts a list of LoggerOption. For example:

var logger, _ = log.NewDefaultLoggerFactory().Create()

is equivalent to:

var logger, _ = log.NewDefaultLoggerFactory().Create(
	log.WithServiceName("default"),   // adds {"service":"default"} to log records
	log.WithLevel(zerolog.InfoLevel), // logs records with level >= info
	log.WithOutputWriter(os.Stdout),  // sends logs records to stdout
)

type LogOutputWriter

type LogOutputWriter int

LogOutputWriter is an enum for the log output writers.

const (
	StdoutOutputWriter LogOutputWriter = iota
	NoopOutputWriter
	TestOutputWriter
	ConsoleOutputWriter
)

func FetchLogOutputWriter

func FetchLogOutputWriter(l string) LogOutputWriter

FetchLogOutputWriter returns a LogOutputWriter for a given value.

func (LogOutputWriter) String

func (l LogOutputWriter) String() string

String returns a string representation of a LogOutputWriter.

type Logger

type Logger struct {
	*zerolog.Logger
}

Logger provides the possibility to generate logs, and inherits of all Zerolog features.

func CtxLogger

func CtxLogger(ctx context.Context) *Logger

CtxLogger retrieves a Logger from a provided context (or creates and appends a new one if missing).

It automatically adds the traceID and spanID log fields depending on current tracing context.

func FromZerolog

func FromZerolog(logger zerolog.Logger) *Logger

FromZerolog converts as Zerolog logger into a Logger.

func (*Logger) ToZerolog

func (l *Logger) ToZerolog() *zerolog.Logger

ToZerolog converts as Logger into a Zerolog logger.

type LoggerFactory

type LoggerFactory interface {
	Create(options ...LoggerOption) (*Logger, error)
}

LoggerFactory is the interface for Logger factories.

func NewDefaultLoggerFactory

func NewDefaultLoggerFactory() LoggerFactory

NewDefaultLoggerFactory returns a DefaultLoggerFactory, implementing LoggerFactory.

type LoggerOption

type LoggerOption func(o *Options)

LoggerOption are functional options for the LoggerFactory implementations.

func WithLevel

func WithLevel(l zerolog.Level) LoggerOption

WithLevel is used to specify the log level to use.

func WithOutputWriter

func WithOutputWriter(w io.Writer) LoggerOption

WithOutputWriter is used to specify the output writer to use.

func WithServiceName

func WithServiceName(n string) LoggerOption

WithServiceName is used to add automatically a service log field value.

type Options

type Options struct {
	ServiceName  string
	Level        zerolog.Level
	OutputWriter io.Writer
}

Options are options for the LoggerFactory implementations.

func DefaultLoggerOptions

func DefaultLoggerOptions() Options

DefaultLoggerOptions are the default options used in the DefaultLoggerFactory.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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