logftxt

package module
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 28 Imported by: 0

README

logftxt GoDoc Build Status Coverage Status

Package logftxt provides an alternative logf Appender and Encoder for colored text logs. It can be used as a more flexible replacement for logftext.

Features

  • Highlighting of log levels, messages, field names, delimiters, arrays, objects, strings, numbers, errors, durations, etc.
  • Built-in themes and external custom themes.
  • Built-in @default and @fancy themes have good support for both dark and light terminals.
  • Built-in configuration file that can easily be replaced with a custom configuration file.
Changing configuration

Built-in configuration file can be easily replaced with custom configuration file by

  • Copying it, editing it, and setting up an environment variable LOGFTXT_CONFIG pointing to the file
    • path/to/my-config.yml for a custom config relative to ~/.config/logftxt
    • ./path/to/my-config.yml for a custom config relative to the current directory
    • /home/root/path/to/my-config.yml for a custom config at an absolute path
  • Loading it manually with LoadConfig or ReadConfig and passing it as an optional parameter to NewAppender or NewEncoder function
Changing theme

Theme can be easily changed by

  • Setting up LOGFTXT_THEME environment variable to a value of
    • @default, @fancy or @legacy for a built-in theme
    • path/to/my-theme.yml for a custom theme relative to ~/.config/logftxt
    • ./path/to/my-theme.yml for a custom theme relative to the current directory
    • /home/root/path/to/my-theme.yml for a custom theme at an absolute path
  • Setting the theme name in the custom configuration file in the same format as the LOGFTXT_THEME environment variable
  • Providing an optional parameter ThemeRef to NewAppender or NewEncoder function containing the same value as the LOGFTXT_THEME environment variable
  • Loading it manually with LoadTheme or ReadTheme and passing it as an optional parameter to NewAppender or NewEncoder function

Example

The following example creates the new logf logger with the logftxt Appender constructed with the default Encoder. The source code can be found in examples/hello.

package main

import (
	"errors"
	"os"
	"runtime"
	"runtime/debug"

	"github.com/ssgreg/logf"

	"github.com/pamburus/logftxt"
)

func main() {
	// Create ChannelWriter with text Encoder with default settings.
	writer, writerClose := logf.NewChannelWriter(logf.ChannelWriterConfig{
		Appender: logftxt.NewAppender(os.Stdout),
	})
	defer writerClose()

	// Create Logger with ChannelWriter.
	logger := logf.NewLogger(logf.LevelDebug, writer).WithCaller().WithName("main")

	// Do some logging.
	logger.Info("runtime info", logf.Int("cpu-count", runtime.NumCPU()))

	if info, ok := debug.ReadBuildInfo(); ok {
		logger.Debug("build info", logf.String("go-version", info.GoVersion), logf.String("path", info.Path))
		for _, setting := range info.Settings {
			logger.Debug("build setting", logf.String("key", setting.Key), logf.String("value", setting.Value))
		}
		for _, dep := range info.Deps {
			logger.Debug("dependency", logf.String("path", dep.Path), logf.String("version", dep.Version))
		}
	} else {
		logger.Warn("couldn't get build info")
	}

	logger.Error("something bad happened", logf.Error(errors.New("failed to figure out what to do next")))
}
Example output

GitHub-Mark-Light GitHub-Mark-Dark

Used terminal color schemes
iTerm2
Alacritty
  • One Dark Neo
    • Note: It is recommended to use draw_bold_text_with_bright_colors: true setting
  • Light
    • Note: It is recommended to use draw_bold_text_with_bright_colors: false setting

Documentation

Overview

Package logftxt provides logf.Appender and logf.Encoder implementations that output log messages in a textual human-readable form.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListBuiltInThemes

func ListBuiltInThemes() ([]string, error)

ListBuiltInThemes returns list of names of all built-in themes.

func NewAppender

func NewAppender(w io.Writer, options ...AppenderOption) logf.Appender

NewAppender returns a new logf.Appender with the given Writer and optional custom configuration.

func NewEncoder

func NewEncoder(options ...EncoderOption) logf.Encoder

NewEncoder constructs a new logf.Encoder that encodes log messages in a human-readable text representation.

Types

type AppenderOption

type AppenderOption interface {
	// contains filtered or unexported methods
}

AppenderOption is an optional parameter for NewAppender.

Applicable types: CallerEncodeFunc, ColorSetting, PoolSizeLimit, Config, ConfigProvideFunc, Environment, FSOption, Theme, ThemeProvideFunc, ThemeEnvironmentRef, ThemeRef, FlattenObjectsSetting, TimestampEncodeFunc, TimeValueEncodeFunc, DurationEncodeFunc, ErrorEncodeFunc.

type CallerEncodeFunc

type CallerEncodeFunc func([]byte, logf.EntryCaller) []byte

CallerEncodeFunc is a function that encodes logf.EntryCaller as a text.

func CallerLong

func CallerLong() CallerEncodeFunc

CallerLong returns a CallerEncodeFunc that encodes caller keeping full file path and line number.

func CallerShort

func CallerShort() CallerEncodeFunc

CallerShort returns a CallerEncodeFunc that encodes caller keeping only package name, base filename and line number.

type CallerFormat

type CallerFormat string

CallerFormat defines duration output format.

const (
	CallerFormatDefault CallerFormat = ""
	CallerFormatShort   CallerFormat = "short"
	CallerFormatLong    CallerFormat = "long"
)

Valid values for CallerFormat.

func (CallerFormat) Validate

func (v CallerFormat) Validate() error

Validate checks whether v has a valid value.

type ColorSetting

type ColorSetting int

ColorSetting allows to explicitly specify preference on using colors and other ANSI SGR escape sequences in output.

const (
	ColorAuto ColorSetting = iota
	ColorNever
	ColorAlways
)

Valid values for ColorSetting.

type Config

type Config struct {
	Theme     ThemeRef `yaml:"theme"`
	Timestamp struct {
		Format string `yaml:"format"`
	} `yaml:"timestamp"`
	Caller struct {
		Format CallerFormat `yaml:"format"`
	} `yaml:"caller"`
	Values struct {
		Time struct {
			Format string `yaml:"format"`
		} `yaml:"time"`
		Duration struct {
			Format    DurationFormat `yaml:"format"`
			Precision Precision      `yaml:"precision"`
		} `yaml:"duration"`
		Error struct {
			Format ErrorFormat `yaml:"format"`
		} `yaml:"error"`
	} `yaml:"values"`
}

Config holds logftxt configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default built-in configuration.

func LoadConfig

func LoadConfig(filename string, opts ...domainOption) (*Config, error)

LoadConfig loads configuration file with the given filename.

func ReadConfig

func ReadConfig(reader io.Reader) (*Config, error)

ReadConfig loads configuration from the given reader.

func (Config) Validate

func (c Config) Validate() error

Validate checks whether c is valid.

type ConfigProvideFunc

type ConfigProvideFunc func(Domain) (*Config, error)

ConfigProvideFunc is a function that provides Config when called. ConfigProvideFunc can return `nil` configuration and `nil` error in case there is no any configuration found at the corresponding source.

func ConfigFromDefaultPath

func ConfigFromDefaultPath(opts ...domainOption) ConfigProvideFunc

ConfigFromDefaultPath returns a ConfigProvideFunc that load configuration from default path that is `~/.config/logftxt/config.yml`. In case there is no such file, `nil` is returned allowing to fallback to other configuration sources.

func ConfigFromEnvironment

func ConfigFromEnvironment(opts ...domainOption) ConfigProvideFunc

ConfigFromEnvironment returns a ConfigProvideFunc that gets configuration filename from environment variable `LOGFTXT_CONFIG`. In case there is no such environment variable, `nil` is returned allowing to fallback to other configuration sources.

type Domain added in v0.2.0

type Domain interface {
	Environment() Environment
	FS() FS
	// contains filtered or unexported methods
}

Domain provides external dependencies.

func DefaultDomain added in v0.2.0

func DefaultDomain() Domain

DefaultDomain returns a default implementation of Domain that uses operating system bindings as dependencies.

func NewDomain added in v0.2.0

func NewDomain(base Domain, options ...domainOption) Domain

NewDomain constructs a new Domain based on the provided base but with some values overridden by the given options.

type DurationEncodeFunc

type DurationEncodeFunc func([]byte, time.Duration) []byte

DurationEncodeFunc is a function that encodes time.Duration values into text.

func DurationAsHMS

func DurationAsHMS(options ...DurationOption) DurationEncodeFunc

DurationAsHMS returns a DurationEncodeFunc that encodes time.Duration values as 'HH:MM:SS.sss' where

HH is number of hours (minimum 2 digits),
MM is number of minutes (always 2 digits),
SS is number of seconds (always 2 digits),
sss is fractional part of seconds (depends on Precision option).

func DurationAsSeconds

func DurationAsSeconds(options ...DurationOption) DurationEncodeFunc

DurationAsSeconds returns a DurationEncodeFunc that encodes time.Duration values as floating point number of seconds.

func DurationAsText

func DurationAsText() DurationEncodeFunc

DurationAsText returns a DurationEncodeFunc that encodes time.Duration values as text with dynamic units. For example, it can be '1ms', '1s', '2m32s'.

type DurationFormat

type DurationFormat string

DurationFormat defines duration output format.

const (
	DurationFormatDefault DurationFormat = ""
	DurationFormatDynamic DurationFormat = "dynamic"
	DurationFormatSeconds DurationFormat = "seconds"
	DurationFormatHMS     DurationFormat = "hms"
)

Valid values for DurationFormat.

func (DurationFormat) Validate

func (v DurationFormat) Validate() error

Validate checks whether v has a valid value.

type DurationOption

type DurationOption interface {
	// contains filtered or unexported methods
}

DurationOption is an optional parameter for DurationAsSeconds and DurationAsHMS. Implemented by:

  • Precision.

type EncoderOption

type EncoderOption interface {
	AppenderOption
	// contains filtered or unexported methods
}

EncoderOption is an optional parameter for NewEncoder.

Applicable types: CallerEncodeFunc, ColorSetting, PoolSizeLimit, Config, ConfigProvideFunc, Environment, FSOption, Theme, ThemeProvideFunc, ThemeEnvironmentRef, ThemeRef, FlattenObjectsSetting, TimestampEncodeFunc, TimeValueEncodeFunc, DurationEncodeFunc, ErrorEncodeFunc.

type Environment

type Environment func(string) (string, bool)

Environment is an environment variable lookup function.

type ErrFileNotFound

type ErrFileNotFound struct {
	Filename string
	// contains filtered or unexported fields
}

ErrFileNotFound is an error that is returned in case file is not found.

func (ErrFileNotFound) Error

func (e ErrFileNotFound) Error() string

Error returns error message.

func (ErrFileNotFound) Is

func (e ErrFileNotFound) Is(err error) bool

Is returns true if e is a sub-class of err.

func (ErrFileNotFound) Unwrap

func (e ErrFileNotFound) Unwrap() error

Unwrap returns original error.

type ErrorEncodeFunc

type ErrorEncodeFunc func([]byte, error) []byte

ErrorEncodeFunc is a function that encodes errors as a text.

func ErrorLong

func ErrorLong() ErrorEncodeFunc

ErrorLong returns an error formatting function that uses "%+v" format and can be used for errors with additional information like those provided by github.com/pkg/errors package.

func ErrorShort

func ErrorShort() ErrorEncodeFunc

ErrorShort returns an error formatting function that just returns error message.

type ErrorFormat

type ErrorFormat string

ErrorFormat defines duration output format.

const (
	ErrorFormatDefault ErrorFormat = ""
	ErrorFormatShort   ErrorFormat = "short"
	ErrorFormatLong    ErrorFormat = "long"
)

Valid values for ErrorFormat.

func (ErrorFormat) Validate

func (v ErrorFormat) Validate() error

Validate checks whether v has a valid value.

type FS

type FS interface {
	ConfigDir() (fs.FS, error)
	Open(filename string) (fs.File, error)
}

FS is an abstract filesystem for accessing configuration files.

func SystemFS added in v0.2.0

func SystemFS() FS

SystemFS constructs default FS implementation that accesses operating system's root filesystem.

type FSOption

type FSOption struct {
	// contains filtered or unexported fields
}

FSOption is an optional parameter created by WithFS that can be used in

  • LoadConfig
  • ConfigFromEnvironment
  • ConfigFromDefaultPath
  • LoadTheme
  • ThemeFromEnvironment.

func WithFS

func WithFS(value FS) FSOption

WithFS returns an FSOption.

type FlattenObjectsSetting added in v0.6.0

type FlattenObjectsSetting bool

FlattenObjectsSetting tells encoder to flatten or not nested objects when encoding.

func FlattenObjects added in v0.6.0

func FlattenObjects(flatten bool) FlattenObjectsSetting

FlattenObjects tells encoder wether to flatten nested objects when encoding.

type PoolSizeLimit

type PoolSizeLimit int

PoolSizeLimit limits size of the pool of pre-allocated entry encoders.

type Precision

type Precision int

Precision can be used to specify exact or automatic precision for formatting floating point values.

const PrecisionAuto Precision = -1

PrecisionAuto is a constant that can be used to request automatic precision selection.

func (Precision) MarshalText

func (p Precision) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interfaces and allows precision to be converted into text.

func (*Precision) UnmarshalText

func (p *Precision) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler interfaces and allows precision to be converted from text.

type Theme

type Theme struct {
	// contains filtered or unexported fields
}

Theme holds formatting and styling settings.

func DefaultTheme

func DefaultTheme() *Theme

DefaultTheme returns default built-in theme.

func LoadBuiltInTheme

func LoadBuiltInTheme(name string) (*Theme, error)

LoadBuiltInTheme loads named built-in theme.

func LoadTheme

func LoadTheme(filename string, opts ...domainOption) (*Theme, error)

LoadTheme loads theme from a file defined by the given filename.

If the filename is relative and does not start with `./` or `../` then the file will be searched in `~/.config/logftxt/themes` folder.

To search file relatively current working directory instead, add explicit `./` or `../` prefix.

func ReadTheme

func ReadTheme(reader io.Reader) (*Theme, error)

ReadTheme reads theme configuration from the given reader.

type ThemeEnvironmentRef added in v0.2.0

type ThemeEnvironmentRef struct {
	// contains filtered or unexported fields
}

ThemeEnvironmentRef is an option that requests to load theme specified by environment variables.

func ThemeFromEnvironment

func ThemeFromEnvironment(opts ...domainOption) ThemeEnvironmentRef

ThemeFromEnvironment returns a ThemeRef that references some theme as defined by the environment variables.

type ThemeProvideFunc

type ThemeProvideFunc func(Domain) (*Theme, error)

ThemeProvideFunc is a function that provides Theme when called.

ThemeProvideFunc can return `nil` theme and `nil` error meaning there is nothing to provide from its source.

type ThemeRef

type ThemeRef struct {
	// contains filtered or unexported fields
}

ThemeRef is a reference to a built-in or external theme. Built-in theme is referenced by '@' prefix following built-in theme name. External theme is referenced by specifying an absolute or relative path to a theme configuration file. Relative path starting with `./` or `../` will request locating the file relatively to the current working directory. Relative path not starting with `./` or `../` will request locating the file relatively to `~/.config/logftxt/themes` directory.

func NewThemeRef

func NewThemeRef(name string, opts ...domainOption) ThemeRef

NewThemeRef constructs a new theme reference with the given name and options.

func (ThemeRef) Load

func (v ThemeRef) Load() (*Theme, error)

Load loads the referenced theme.

func (ThemeRef) MarshalText

func (v ThemeRef) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface.

func (ThemeRef) String

func (v ThemeRef) String() string

String returns theme reference name.

func (*ThemeRef) UnmarshalText

func (v *ThemeRef) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler interface.

type TimeEncodeFunc

type TimeEncodeFunc func([]byte, time.Time) []byte

TimeEncodeFunc is a function that encodes time.Time into text.

func TimeLayout

func TimeLayout(layout string) TimeEncodeFunc

TimeLayout returns TimeEncodeFunc that encodes time using the given layout.

func (TimeEncodeFunc) TimeValue

func (f TimeEncodeFunc) TimeValue() TimeValueEncodeFunc

TimeValue returns a TimeValueEncodeFunc that encodes time values into text the same way.

func (TimeEncodeFunc) Timestamp

func (f TimeEncodeFunc) Timestamp() TimestampEncodeFunc

Timestamp returns a TimestampEncodeFunc that encodes timestamp into text the same way.

type TimeValueEncodeFunc

type TimeValueEncodeFunc TimeEncodeFunc

TimeValueEncodeFunc is a function that encodes time field values into text.

type TimestampEncodeFunc

type TimestampEncodeFunc TimeEncodeFunc

TimestampEncodeFunc is a function that encodes log message timestamp into text.

Directories

Path Synopsis
examples
internal
pkg/cfgdir
Package cfgdir provides helpers for dealing with configuration directories.
Package cfgdir provides helpers for dealing with configuration directories.
pkg/env
Package env provides accessors to the known environment variables.
Package env provides accessors to the known environment variables.
pkg/pathx
Package pathx provides additional utilities for working with paths.
Package pathx provides additional utilities for working with paths.
pkg/quoting
Package quoting provides helpers to determine if a string needs to be quoted.
Package quoting provides helpers to determine if a string needs to be quoted.
pkg/themecfg
Package themecfg defines configuration file format for a logftxt theme.
Package themecfg defines configuration file format for a logftxt theme.
pkg/themecfg/formatting
Package formatting provides formatting configuration section for slogtxt theme configuration.
Package formatting provides formatting configuration section for slogtxt theme configuration.

Jump to

Keyboard shortcuts

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