log

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2023 License: MIT Imports: 18 Imported by: 1,963

README

Log

Latest Release GoDoc Build Status Go ReportCard

A minimal and colorful Go logging library. 🪵

Demo

It provides a leveled structured human readable logger with a small API. Unlike standard log, the Charm logger provides customizable colorful human readable logging with batteries included.

  • Uses lipgloss to style and colorize the output.
  • Beautiful human readable format.
  • Ability to customize the time stamp format.
  • Skips caller frames and marks function as helpers.
  • Leveled logging with the ability to turn off logging altogether.
  • Store and retrieve logger in and from context.
  • Standard log Adapter.

Usage

The Charm logger comes with a global package-wise logger with timestamps turned on and the logging level set to info.

log.Debug("cookie 🍪") // won't print anything
log.Info("Hello World!") // 2023/01/04 10:04:06 INFO Hello World!

All logging levels accept optional key/value pairs to be printed along with the message.

err := fmt.Errorf("too much sugar")
log.Error("failed to bake cookies", "err", err, "butter", "1 cup")
// 2023/01/04 10:04:06 ERROR failed to bake cookies err="too much sugar" butter="1 cup"

You can use log.Print() to print messages without a level prefix.

log.Print("Baking 101") // 2023/01/04 10:04:06 Baking 101
New loggers

Use New() to create new loggers.

logger := log.New()
if butter {
    logger.Warn("chewy!", "butter", true) // WARN chewy! butter=true
}
Options

You can customize the logger with options. Use log.WithCaller() to enable printing source location. log.WithTimestamp() prints the timestamp of each log.

logger := log.New(log.WithTimestamp(), log.WithTimeFormat(time.Kitchen),
    log.WithCaller(), log.WithPrefix("baking 🍪"))
logger.Info("Starting oven!", "degree", 375)
// 10:00AM INFO <cookies/oven.go:56> baking 🍪: Starting oven! degree=375
time.Sleep(10 * time.Minute)
logger.Info("Finished baking")
// 10:10AM INFO <cookies/oven.go:60> baking 🍪: Finished baking

Use log.SetFormatter() or log.WithFormatter() to change the output format. Available options are:

  • log.TextFormatter (default)
  • log.JSONFormatter
  • log.LogfmtFormatter

For a list of available options, refer to options.go.

Set the logger level and options.

logger.SetReportTimestamp(false)
logger.SetReportCaller(false)
logger.SetLevel(log.DebugLevel)
logger.Debug("Preparing batch 2...") // DEBUG baking 🍪: Preparing batch 2...
Sub-logger

Create sub-loggers with their specific fields.

batch2 := logger.With("batch", 2, "chocolateChips", true)
batch2.Debug("Adding chocolate chips")
// DEBUG <cookies/oven.go:68> baking 🍪: Adding chocolate chips batch=2 chocolateChips=true
Format Messages

You can use fmt.Sprintf() to format messages.

for item := 1; i <= 100; i++ {
    log.Info(fmt.Sprintf("Baking %d/100...", item))
    // INFO Baking 1/100...
    // INFO Baking 2/100...
    // INFO Baking 3/100...
    // ...
    // INFO Baking 100/100...
}

Or arguments:

for temp := 375; temp <= 400; temp++ {
    log.Info("Increasing temperature", "degree", fmt.Sprintf("%d°F", temp))
    // INFO Increasing temperature degree=375°F
    // INFO Increasing temperature degree=376°F
    // INFO Increasing temperature degree=377°F
    // ...
    // INFO Increasing temperature degree=400°F
}
Helper Functions

Skip caller frames in helper functions. Similar to what you can do with testing.TB().Helper().

function startOven(degree int) {
    log.Helper()
    log.Info("Starting oven", "degree", degree)
}

log.SetReportCaller(true)
startOven(400) // INFO <cookies/oven.go:123> Starting oven degree=400

This will use the caller function (startOven) line number instead of the logging function (log.Info) to report the source location.

Standard Log Adapter

Some Go libraries, especially the ones in the standard library, will only accept the standard logger interface. For instance, the HTTP Server from net/http will only take a *log.Logger for its ErrorLog field.

For this, you can use the standard log adapter which simply wraps the logger in a *log.Logger interface.

stdlog := log.New(log.WithPrefix("http")).StandardLog(log.StandardLogOption{
    ForceLevel: log.ErrorLevel,
})
s := &http.Server{
    Addr:     ":8080",
    Handler:  handler,
    ErrorLog: stdlog,
}
stdlog.Printf("Failed to make bake request, %s", fmt.Errorf("temperature is to low"))
// ERROR http: Failed to make bake request, temperature is to low

License

MIT


Part of Charm.

the Charm logo

Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة

Documentation

Index

Constants

View Source
const DefaultTimeFormat = "2006/01/02 15:04:05"

DefaultTimeFormat is the default time format.

Variables

View Source
var (
	// TimestampStyle is the style for timestamps.
	TimestampStyle = lipgloss.NewStyle()

	// CallerStyle is the style for caller.
	CallerStyle = lipgloss.NewStyle().Faint(true)

	// PrefixStyle is the style for prefix.
	PrefixStyle = lipgloss.NewStyle().Bold(true).Faint(true)

	// MessageStyle is the style for messages.
	MessageStyle = lipgloss.NewStyle()

	// KeyStyle is the style for keys.
	KeyStyle = lipgloss.NewStyle().Faint(true)

	// ValueStyle is the style for values.
	ValueStyle = lipgloss.NewStyle()

	// SeparatorStyle is the style for separators.
	SeparatorStyle = lipgloss.NewStyle().Faint(true)

	// DebugLevel is the style for debug level.
	DebugLevelStyle = lipgloss.NewStyle().
					SetString("DEBUG").
					Bold(true).
					MaxWidth(4).
					Foreground(lipgloss.AdaptiveColor{
			Light: "63",
			Dark:  "63",
		})

	// InfoLevel is the style for info level.
	InfoLevelStyle = lipgloss.NewStyle().
					SetString("INFO").
					Bold(true).
					MaxWidth(4).
					Foreground(lipgloss.AdaptiveColor{
			Light: "39",
			Dark:  "86",
		})

	// WarnLevel is the style for warn level.
	WarnLevelStyle = lipgloss.NewStyle().
					SetString("WARN").
					Bold(true).
					MaxWidth(4).
					Foreground(lipgloss.AdaptiveColor{
			Light: "208",
			Dark:  "192",
		})

	// ErrorLevel is the style for error level.
	ErrorLevelStyle = lipgloss.NewStyle().
					SetString("ERROR").
					Bold(true).
					MaxWidth(4).
					Foreground(lipgloss.AdaptiveColor{
			Light: "203",
			Dark:  "204",
		})

	// FatalLevel is the style for error level.
	FatalLevelStyle = lipgloss.NewStyle().
					SetString("FATAL").
					Bold(true).
					MaxWidth(4).
					Foreground(lipgloss.AdaptiveColor{
			Light: "133",
			Dark:  "134",
		})
)
View Source
var (
	// ErrMissingValue is returned when a key is missing a value.
	ErrMissingValue = fmt.Errorf("missing value")
)

Functions

func Debug

func Debug(msg interface{}, keyvals ...interface{})

Debug logs a debug message.

func Error

func Error(msg interface{}, keyvals ...interface{})

Error logs an error message.

func Fatal

func Fatal(msg interface{}, keyvals ...interface{})

Fatal logs a fatal message and exit.

func GetPrefix

func GetPrefix() string

GetPrefix returns the prefix for the default logger.

func Helper

func Helper()

Helper marks the calling function as a helper and skips it for source location information. It's the equivalent of testing.TB.Helper().

func Info

func Info(msg interface{}, keyvals ...interface{})

Info logs an info message.

func NowUTC

func NowUTC() time.Time

NowUTC is a convenient function that returns the current time in UTC timezone.

This is to be used as a time function. For example:

log.SetTimeFunction(log.NowUTC)

func Print

func Print(msg interface{}, keyvals ...interface{})

Print logs a message with no level.

func SetFormatter

func SetFormatter(f Formatter)

SetFormatter sets the formatter for the default logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets the level for the default logger.

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the output for the default logger.

func SetPrefix

func SetPrefix(prefix string)

SetPrefix sets the prefix for the default logger.

func SetReportCaller

func SetReportCaller(report bool)

SetReportCaller sets whether to report caller location for the default logger.

func SetReportTimestamp

func SetReportTimestamp(report bool)

SetReportTimestamp sets whether to report timestamp for the default logger.

func SetTimeFormat

func SetTimeFormat(format string)

SetTimeFormat sets the time format for the default logger.

func SetTimeFunction

func SetTimeFunction(f TimeFunction)

SetTimeFunction sets the time function for the default logger.

func StandardLog

func StandardLog(opts ...StandardLogOption) *log.Logger

StandardLog returns a standard logger from the default logger.

func Warn

func Warn(msg interface{}, keyvals ...interface{})

Warn logs a warning message.

func WithContext

func WithContext(ctx context.Context, logger Logger, keyvals ...interface{}) context.Context

WithContext wraps the given logger in context.

Types

type Formatter

type Formatter uint8

Formatter is a formatter for log messages.

const (
	// TextFormatter is a formatter that formats log messages as text. Suitable for
	// console output and log files.
	TextFormatter Formatter = iota
	// JSONFormatter is a formatter that formats log messages as JSON.
	JSONFormatter
	// LogfmtFormatter is a formatter that formats log messages as logfmt.
	LogfmtFormatter
)

type Level

type Level int32

Level is a logging level.

const (
	// DebugLevel is the debug level.
	DebugLevel Level = iota
	// InfoLevel is the info level.
	InfoLevel
	// WarnLevel is the warn level.
	WarnLevel
	// ErrorLevel is the error level.
	ErrorLevel
	// FatalLevel is the fatal level.
	FatalLevel
)

func GetLevel

func GetLevel() Level

GetLevel returns the level for the default logger.

func (Level) String

func (l Level) String() string

String returns the string representation of the level.

type Logger

type Logger interface {
	// SetLevel sets the allowed level.
	SetLevel(level Level)
	// GetLevel returns the allowed level.
	GetLevel() Level

	// SetPrefix sets the logger prefix. The default is no prefix.
	SetPrefix(prefix string)
	// GetPrefix returns the logger prefix.
	GetPrefix() string

	// SetReportTimestamp sets whether the logger should report the timestamp.
	SetReportTimestamp(bool)
	// SetReportCaller sets whether the logger should report the caller location.
	SetReportCaller(bool)
	// SetTimeFunction sets the time function used to get the time.
	// The default is time.Now.
	//
	// To use UTC time instead of local time set the time
	// function to `NowUTC`.
	SetTimeFunction(f TimeFunction)
	// SetTimeFormat sets the time format. The default is "2006/01/02 15:04:05".
	SetTimeFormat(format string)
	// SetOutput sets the output destination. The default is os.Stderr.
	SetOutput(w io.Writer)
	// SetFormatter sets the formatter. The default is TextFormatter.
	SetFormatter(f Formatter)

	// Helper marks the calling function as a helper
	// and skips it for source location information.
	// It's the equivalent of testing.TB.Helper().
	Helper()

	// With returns a new sub logger with the given key value pairs.
	With(keyval ...interface{}) Logger

	// Debug logs a debug message.
	Debug(msg interface{}, keyval ...interface{})
	// Info logs an info message.
	Info(msg interface{}, keyval ...interface{})
	// Warn logs a warning message.
	Warn(msg interface{}, keyval ...interface{})
	// Error logs an error message.
	Error(msg interface{}, keyval ...interface{})
	// Fatal logs a fatal message.
	Fatal(msg interface{}, keyval ...interface{})
	// Print logs a message with no level.
	Print(msg interface{}, keyval ...interface{})

	// StandardLog returns a standard logger from this logger.
	StandardLog(...StandardLogOption) *log.Logger
}

Logger is an interface for logging.

func Default

func Default() Logger

Default returns the default logger. The default logger comes with timestamp enabled.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext returns the logger from the given context. This will return the default package logger if no logger found in context.

func New

func New(opts ...LoggerOption) Logger

New returns a new logger. It uses os.Stderr as the default output.

func With

func With(keyvals ...interface{}) Logger

With returns a new logger with the given keyvals.

type LoggerOption

type LoggerOption = func(*logger)

LoggerOption is an option for a logger.

func WithCaller

func WithCaller() LoggerOption

WithCaller returns a LoggerOption that enables caller for the logger.

func WithFields

func WithFields(keyvals ...interface{}) LoggerOption

WithFields returns a LoggerOption that sets the fields for the logger.

func WithFormatter

func WithFormatter(f Formatter) LoggerOption

WithFormatter returns a LoggerOption that sets the formatter for the logger.

func WithLevel

func WithLevel(level Level) LoggerOption

WithLevel returns a LoggerOption that sets the level for the logger. The default is InfoLevel.

func WithOutput

func WithOutput(w io.Writer) LoggerOption

WithOutput returns a LoggerOption that sets the output for the logger. The default is os.Stderr.

func WithPrefix

func WithPrefix(prefix string) LoggerOption

WithPrefix returns a LoggerOption that sets the prefix for the logger.

func WithTimeFormat

func WithTimeFormat(format string) LoggerOption

WithTimeFormat returns a LoggerOption that sets the time format for the logger. The default is "2006/01/02 15:04:05".

func WithTimeFunction

func WithTimeFunction(f TimeFunction) LoggerOption

WithTimeFunction returns a LoggerOption that sets the time function for the logger. The default is time.Now.

func WithTimestamp

func WithTimestamp() LoggerOption

WithTimestamp returns a LoggerOption that enables timestamps for the logger.

type StandardLogOption

type StandardLogOption struct {
	ForceLevel Level
}

StandardLogOption can be used to configure the standard log adapter.

type TimeFunction

type TimeFunction = func() time.Time

TimeFunction is a function that returns a time.Time.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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