logy

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 20 Imported by: 2

README

Logy logo

Go Report Card CircleCI codecov

Logy

The Logy is a fast, configurable, and easy-to-use logger for Go applications. It supports various logging levels, handlers, and hierarchically named loggers.

Getting Started

Installation

To use Logy in your Go project, you need to first install it using the following command:

go get -u codnect.io/logy

After installing Logy, you can import it in your Go code like this:

import "codnect.io/logy"

Once you've imported Logy, you can start using it to log messages.

Usage

Here's an example of how to use Logy:

package main

import (
    "context"
    "codnect.io/logy"
)

func main() {
    // logy.Get() creates a logger with the name of the package it is called from
    log := logy.Get()

    // Logging messages with different log levels
    log.Info("This is an information message")
    log.Warn("This is a warning message")
    log.Error("This is an error message")
    log.Debug("This is a debug message")
    log.Trace("This is a trace message")
}

The above code produces the following result.

Output

If you want to add contextual fields to your log messages, you can use the logy.WithValue() function to create a new context with the desired fields. This function returns a new context with the additional field(s) and copies any existing contextual fields from the original context.

You can then use the new context to log messages with contextual fields using the I(), W(), E(), D(), and T() methods. These methods accept the context as the first argument, followed by the log message itself.

package main

import (
    "context"
    "codnect.io/logy"
)

func main() {
    // logy.Get() creates a logger with the name of the package it is called from
    log := logy.Get()

    // Change console log format
    err := logy.LoadConfig(&logy.Config{
        Console: &logy.ConsoleConfig{
            Enabled: true,
            Format:  "%d{2006-01-02 15:04:05.000} %l [%x{traceId},%x{spanId}] %p %c : %s%e%n",
            Color:   true,
        },
    })

    if err != nil {
        panic(err)
    }

    // logy.WithValue() returns a new context with the given field and copies any 
    // existing contextual fields if they exist.
    // This ensures that the original context is not modified and avoids any potential 
    // issues.
    ctx := logy.WithValue(context.Background(), "traceId", "anyTraceId")
    // It will create a new context with the spanId and copies the existing fields
    ctx = logy.WithValue(ctx, "spanId", "anySpanId")

    // Logging messages with contextual fields
    log.I(ctx, "info message")
    log.W(ctx, "warning message")
    log.E(ctx, "error message")
    log.D(ctx, "debug message")
    log.T(ctx, "trace message")
}

The above code produces the following result.

Output

if you want to add a contextual field to an existing context, you can use the logy.PutValue() function to directly modify the context. However, note that this should not be done across multiple goroutines as it is not safe.

// It will put the field into original context, so the original context is changed.
logy.PutValue(ctx, "traceId", "anotherTraceId")
Parameterized Logging

Logy provides support for parameterized log messages.

package main

import (
    "context"
    "codnect.io/logy"
)

func main() {
    // logy.Get() creates a logger with the name of the package it is called from
    log := logy.Get()
	
    value := 30
    // Logging a parameterized message
    log.Info("The value {} should be between {} and {}", value, 128, 256)
}

The output of the above code execution looks as follows:

2023-03-19 21:13:06.029186  INFO codnect.io/logy/test    : The value 30 should be between 128 and 256
Setting Logy As Default Logger

SetAsDefaultLogger sets logy as default logger, so that existing applications that use log.Printf and related functions will send log records to logy's handlers.

Here is the way of how to set logy as default logger:

logy.SetAsDefaultLogger()
JSON Logging Format

Here is an example of how to enable the JSON formatting for console handler.

package main

import (
    "context"
    "codnect.io/logy"
)

func main() {
    // logy.Get() creates a logger with the name of the package it is called from
    log := logy.Get()
	
    // Enabled the Json logging
    err := logy.LoadConfig(&logy.Config{
        Console: &logy.ConsoleConfig{
            Enabled: true,
            Json: &logy.JsonConfig{
                Enabled: true,
            },
        },
    })

    if err != nil {
       panic(err)
    }

    // logy.WithValue() returns a new context with the given field and copies any
    // existing contextual fields if they exist.
    ctx := logy.WithValue(context.Background(), "traceId", "anyTraceId")
    // It will create a new context with the spanId and copies the existing fields
    ctx = logy.WithValue(ctx, "spanId", "anySpanId")

    // Logging an information message
    log.Info("This is an information message")

    // Logging an information message with contextual fields
    log.I(ctx, "info message")
}

The output of the above code execution looks as follows:

{"timestamp":"2023-03-20T20:59:02+03:00","level":"INFO","logger":"codnect.io/logy/test","message":"This is an information message"}
{"timestamp":"2023-03-20T20:59:02+03:00","level":"INFO","logger":"codnect.io/logy/test","message":"info message","mappedContext":{"traceId":"anyTraceId","spanId":"anySpanId"}}
Error and Stack Trace Logging

If you pass an error to the logging methods as the last argument, it will print the full stack trace along with the given error.

Here is an example:

package main

import (
    "context"
    "errors"
    "codnect.io/logy"
)

func main() {
    // logy.Get() creates a logger with the name of the package it is called from
    log := logy.Get()
	
    value := "anyValue"
    err := errors.New("an error occurred")

    // Note that there must not be placeholder(curly braces) for the error. 
    // Otherwise, the only error string will be printed.
    log.Info("The value {} was not inserted", value, err)
    log.Warn("The value {} was not inserted", value, err)
    log.Error("The value {} was not inserted", value, err)
    log.Debug("The value {} was not inserted", value, err)
    log.Error("The value {} was not inserted", value, err)
}

The output of the above code execution looks as follows:

2023-03-20 21:17:03.165347  INFO codnect.io/logy/test    : The value anyValue was not inserted
Error: an error occurred
main.main()
    /Users/burakkoken/GolandProjects/procyon-projects/logy/test/main.go:19
2023-03-20 21:17:03.165428  WARN codnect.io/logy/test    : The value anyValue was not inserted
Error: an error occurred
main.main()
    /Users/burakkoken/GolandProjects/procyon-projects/logy/test/main.go:20
2023-03-20 21:17:03.165434 ERROR codnect.io/logy/test    : The value anyValue was not inserted
Error: an error occurred
main.main()
    /Users/burakkoken/GolandProjects/procyon-projects/logy/test/main.go:21
2023-03-20 21:17:03.165438 DEBUG codnect.io/logy/test    : The value anyValue was not inserted
Error: an error occurred
main.main()
    /Users/burakkoken/GolandProjects/procyon-projects/logy/test/main.go:22
2023-03-20 21:17:03.165441 ERROR codnect.io/logy/test    : The value anyValue was not inserted
Error: an error occurred
main.main()
    /Users/burakkoken/GolandProjects/procyon-projects/logy/test/main.go:23
Loggers

A Logger instance is used to log messages for an application. Loggers are named, using a hierarchical dot and slash separated namespace.

For example, the logger named github.com/procyon-projects is a parent of the logger named codnect.io/logy. Similarly, net is a parent of net/http and an ancestor of net/http/cookiejar

Logger names can be arbitrary strings, however it's recommended that they are based on the package name or struct name of the logged component.

Logging messages will be forwarded to handlers attached to the loggers.

Creating Logger

Logy provides multiple ways of creating a logger. You can either create a new logger with the logy.Get() function, which creates a named logger with the name of the package it is called from:

log := logy.Get()

For example, a logger created in the codnect.io/logy package would have the name codnect.io/logy.

Alternatively, you can use the logy.Named() function to create a named logger with a specific name:

log := logy.Named("myLogger")

This will create a logger with the given name.

You can also use the logy.Of() method to create a logger for a specific type:

log := logy.Of[http.Client]

This will create a logger with the name net/http.Client.

Invoking the logy.Named() function with the same name or the logy.Get()function in the same package will return always the exact same Logger.

// x and y loggers will be the same
x = logy.Named("foo")
y = logy.Named("foo")

// z and q loggers will be the same
z = logy.Get()
q = logy.Get()

Log Handlers

A log handler is a logging component that sends log messages to a writer. Logy includes the following log handlers:

Console Log Handler

The console log handler is enabled by default. It outputs all log messages to the console of your application. (typically to the system's stdout)

File Log Handler

The file log handler is disabled by default. It outputs all log messages to a file. Note that there is no support log file rotation.

Syslog Log Handler

The syslog log handler is disabled by default. It send all log messages to a syslog server (by default, the syslog server runs on the same host as the application)

External Log Handler

If you want a custom log handler, you can create your own log handler by implementing logy.Handler interface. After completing its implementation, you must register it by using logy.RegisterHandler function.

type Handler interface {
    Handle(record Record) error
    SetLevel(level Level)
    Level() Level
    SetEnabled(enabled bool)
    IsEnabled() bool
    IsLoggable(record Record) bool
    Writer() io.Writer
}

Here is an example of how you can register your custom handlers:

// CustomHandler implements the Handler interface
type CustomHandler struct {
	
}

func newCustomHandler() *CustomHandler {
    return &CustomHandler{...}
}
...

func init() {
    logy.RegisterHandler("handlerName", newCustomHandler())
}

Logging Configuration

In order to configure the logging, you can use the following approaches:

  • Environment Variables
  • Programmatically

You can load the yaml logging configuration files as shown below.

func init() {
    err := logy.LoadConfigFromYaml("logy.config.yaml")
	
    if err != nil {
        panic(err)
    }
}

As an alternative, you can configure the logging by invoking logy.LoadConfig() function.

func init() {
    err := logy.LoadConfig(&logy.Config{
        Level:    logy.LevelTrace,
        Handlers: logy.Handlers{"console", "file"},
        Console: &logy.ConsoleConfig{
            Level:   logy.LevelTrace,
            Enabled: true,
            // this will be ignored because console json logging is enabled
            Format: "%d{2006-01-02 15:04:05.000} %l [%x{traceId},%x{spanId}] %p : %s%e%n",
            Color:   true,
            Json:    &logy.JsonConfig{
                Enabled: true,
                KeyOverrides: logy.KeyOverrides{
                    "timestamp": "@timestamp",
                },
                AdditionalFields: logy.JsonAdditionalFields{
                    "application-name": "my-logy-app",
                },
            },
        },
        File: &logy.FileConfig{
            Enabled: true,
            Name: "file_trace.log",
            Path: "/var",
            // this will be ignored because file json logging is enabled
            Format: "d{2006-01-02 15:04:05} %p %s%e%n",
            Json:    &logy.JsonConfig{
                Enabled: true,
                KeyOverrides: logy.KeyOverrides{
                    "timestamp": "@timestamp",
                },
                AdditionalFields: logy.JsonAdditionalFields{
                    "application-name": "my-logy-app",
                },
            },
        },
    })

    if err != nil {
        panic(err)
    }

}
Logging Package

Logging is done on a per-package basis. Each package can be independently configured. A configuration which applies to a package will also apply to all sub-categories of that package, unless there is a more specific matching sub-package configuration.

For every package the same settings that are configured on ( console / file / syslog ) apply.

Property Description Type Default
logy.package.package-path.level The log level for this package bool TRACE
logy.package.package-path.use-parent-handlers Specify whether this logger should user its parent handlers bool true
logy.package.package-path.handlers The names of the handlers to link to this package list of string
Root Logger Configuration

The root logger is handled separately, and is configured via the following properties:

Property Description Type Default
logy.level The log level for every log package bool TRACE
logy.handlers The names of handlers to link to the root list of string [console]
Logging Format

By default, Logy uses a pattern-based logging format.

You can customize the format for each log handler using a dedicated configuration property. For the console handler, the property is logy.console.format.

The following table shows the logging format string symbols that you can use to configure the format of the log messages.

Supported logging format symbols:

Symbol Summary Description
%% % A simple %%character
%c Logger name The logger name
%C Package name The package name
%d{layout} Date Date with the given layout string
%e Error The error stack trace
%F Source file The source file name
%i Process ID The current process PID
%l Source location The source location(file name, line number, method name)
%L Source line The source line number
%m Full Message The log message including error trace
%M Source method The source method name
%n Newline The line separator string
%N Process name The name of the current process
%p Level The logging level of the message
%s Simple message The log message without error trace
%X{property-name} Mapped Context Value The value from Mapped Context property-key=property-value
%x{property-name} Mapped Context Value without key The value without key from Mapped Context in format property-value
%X Mapped Context Values All the values from Mapped Context in format property-key1=property-value1,property-key2=property-value2
%x Mapped Context Values without keys All the values without keys from Mapped Context in format property-value1,property-value2
Console Handler Properties

You can configure the console handler with the following configuration properties:

Property Description Type Default
logy.console.enabled Enable the console logging bool true
logy.console.target Override keys with custom values Target(stdout, stderr, discard) stdout
logy.console.format The console log format. Note that this value will be ignored if json is enabled for console string d{2006-01-02 15:04:05.000000} %p %c : %m%n
logy.console.color Enable color coded output if the target terminal supports it bool true
logy.console.level The console log level Level(OFF,ERROR,WARN,INFO,DEBUG,TRACE,ALL) TRACE
logy.console.json.enabled Enable the JSON console formatting bool false
logy.console.json.excluded-keys Keys to be excluded from the Json output list of string
logy.console.json.key-overrides.property-name Override keys with custom values map[string]string
logy.console.json.additional-fields.property-name Additional field values map[string]any
File Handler Properties

You can configure the file handler with the following configuration properties:

Property Description Type Default
logy.file.enabled Enable the file logging bool false
logy.file.format The file log format. Note that this value will be ignored if json is enabled for file string d{2006-01-02 15:04:05.000000} %p %c : %m%n
logy.file.name The name of the file in which logs will be written string logy.log
logy.file.path The path of the file in which logs will be written string Working directory
logy.file.level The level of logs to be written into the file Level(OFF,ERROR,WARN,INFO,DEBUG,TRACE,ALL) TRACE
logy.file.json.enabled Enable the JSON file formatting bool false
logy.file.json.excluded-keys Keys to be excluded from the Json output list of string
logy.file.json.key-overrides.property-name Override keys with custom values map[string]string
logy.file.json.additional-fields.property-name Additional field values map[string]any
Syslog Handler Properties

You can configure the syslog handler with the following configuration properties:

Property Description Type Default
logy.syslog.enabled Enable the syslog logging bool false
logy.syslog.endpoint The IP address and port of the syslog server host:port localhost:514
logy.syslog.app-name The app name used when formatting the message in RFC5424 format string
logy.syslog.hostname The name of the host the messages are being sent from string
logy.syslog.facility The facility used when calculating the priority of the message in RFC5424 and RFC3164 format Facility(kernel,user-level,mail-system,system-daemons,security,syslogd,line-printer,network-news,uucp,clock-daemon,security2,ftp-daemon,ntp,log-audit,log-alert,clock-daemon2,local-use-0,local-use-1,local-use-2,local-use-3,local-use-4,local-use-5,local-use-6,local-use-7 user-level
logy.syslog.log-type The message format type used when formatting the message SysLogType(rfc5424,rfc3164) rfc5424
logy.syslog.protocol The protocol used to connect to the syslog server Protocol(tcp,udp) tcp
logy.syslog.block-on-reconnect Enable or disable blocking when attempting to reconnect the syslog server bool false
logy.syslog.format The log message format string d{2006-01-02 15:04:05.000000} %p %c : %m%n
logy.syslog.level The level of the logs to be logged by syslog logger Level(OFF,ERROR,WARN,INFO,DEBUG,TRACE,ALL) TRACE

Examples YAML Logging Configuration

Console Logging Configuration

logy:
  level: INFO

  console:
    enabled: true
    # Send output to stderr
    target: stderr
    format: "%d{2006-01-02 15:04:05.000} %l [%x{traceId},%x{spanId}] %p : %s%e%n"
    # Disable color coded output
    color: false
    level: DEBUG

Console YAML Logging Configuration

logy:
  level: INFO
  console:
    enabled: true
    # Send output to stderr
    target: stderr
    level: DEBUG
    json:
      enabled: true
      excluded-keys:
        - level
        - logger
      key-overrides:
        timestamp: "@timestamp"
      additional-fields:
        application-name: "my-logy-app"

Note that console log will only contain INFO or higher order logs because we set the root logger level to INFO.

File Logging Configuration

logy:
  level: INFO
  file:
    enabled: true
    level: TRACE
    format: "d{2006-01-02 15:04:05} %p %s%e%n"
    # Send output to a file_trace.log under the /var directory
    name: file_trace.log
    path: /var

File YAML Logging Configuration

logy:
  level: INFO
  file:
    enabled: true
    level: TRACE
    # Send output to a file_trace.log under the /var directory
    name: file_trace.log
    path: /var
    json:
      enabled: true
      excluded-keys:
        - level
        - logger
      key-overrides:
        timestamp: "@timestamp"
      additional-fields:
        application-name: "my-logy-app"

Note that file log will only contain INFO or higher order logs because we set the root logger level to INFO.

Performance

Here is the benchmark results.

Log a message without context fields:

Package Time Objects Allocated
⭐ logy 62.04 ns/op 0 allocs/op
⭐ logy(formatting) 1287 ns/op 7 allocs/op
⚡ exp/slog 38.08 ns/op 0 allocs/op
zerolog 37.49 ns/op 0 allocs/op
zerolog(formatting) 3030 ns/op 108 allocs/op
zap 98.30 ns/op 0 allocs/op
zap sugar 110.9 ns/op 1 allocs/op
zap sugar (formatting) 3369 ns/op 108 allocs/op
go-kit 248.5 ns/op 9 allocs/op
log15 2490 ns/op 20 allocs/op
apex/log 1139 ns/op 6 allocs/op
logrus 1831 ns/op 23 allocs/op

Log a message with a logger that already has 10 fields of context:

Package Time Objects Allocated
⭐ logy 85.29 ns/op 0 allocs/op
⭐ logy(formatting) 1369.0 ns/op 7 allocs/op
⚡ exp/slog 266.3 ns/op 0 allocs/op
zerolog 44.84 ns/op 0 allocs/op
zerolog(formatting) 3103.0 ns/op 108 allocs/op
zap 92.50 ns/op 0 allocs/op
zap sugar 113.7 ns/op 1 allocs/op
zap sugar (formatting) 3355 ns/op 108 allocs/op
go-kit 3628 ns/op 66 allocs/op
log15 12532 ns/op 130 allocs/op
apex/log 14494 ns/op 53 allocs/op
logrus 16246 ns/op 68 allocs/op

See logy-benchmarks for more comprehensive and up-to-date benchmarks.

Stargazers

Forkers

License

Logy is released under MIT License.

Documentation

Index

Constants

View Source
const (
	DefaultTextFormat = "%d{2006-01-02 15:04:05.000000} %p %c : %s%e%n"

	DefaultLogFileName = "logy.log"
	DefaultLogFilePath = "."

	DefaultSyslogFormat   = "%d %p %s%e%n"
	DefaultSyslogEndpoint = "localhost:514"

	PropertyLevel   = "level"
	PropertyEnabled = "enabled"
)
View Source
const (
	TimestampKey     = "timestamp"
	MappedContextKey = "mapped_context"
	LevelKey         = "level"
	LoggerKey        = "logger"
	MessageKey       = "message"
	ErrorKey         = "error"
	StackTraceKey    = "stack_trace"
)
View Source
const (
	ConsoleHandlerName = "console"
	FileHandlerName    = "file"
	SyslogHandlerName  = "syslog"
)
View Source
const ContextFieldsKey = "logyContextFields"
View Source
const (
	RootLoggerName = "root"
)

Variables

This section is empty.

Functions

func LoadConfig

func LoadConfig(cfg *Config) error

func LoadConfigFromYaml

func LoadConfigFromYaml(name string) error

func PutValue

func PutValue(ctx context.Context, key string, value any)

func RegisterHandler

func RegisterHandler(name string, handler Handler)

func SetAsDefaultLogger

func SetAsDefaultLogger()

func SupportsColor

func SupportsColor() bool

func WithContextFields

func WithContextFields(parent context.Context) context.Context

func WithValue

func WithValue(parent context.Context, key string, value any) context.Context

Types

type AdditionalFields

type AdditionalFields map[string]any

type ArrayEncoder

type ArrayEncoder interface {
	AppendAny(any) error
	AppendObject(ObjectMarshaler) error
	AppendArray(ArrayMarshaler) error

	AppendString(string)
	AppendStrings([]string)

	AppendByteString([]byte)

	AppendInt(int)
	AppendInts([]int)

	AppendInt8(int8)
	AppendInt8s([]int8)

	AppendInt16(int16)
	AppendInt16s([]int16)

	AppendInt32(int32)
	AppendInt32s([]int32)

	AppendInt64(int64)
	AppendInt64s([]int64)

	AppendUint(uint)
	AppendUints([]uint)

	AppendUint8(uint8)
	AppendUint8s([]uint8)

	AppendUint16(uint16)
	AppendUint16s([]uint16)

	AppendUint32(uint32)
	AppendUint32s([]uint32)

	AppendUint64(uint64)
	AppendUint64s([]uint64)

	AppendUintptr(uintptr)
	AppendUintptrs([]uintptr)

	AppendBool(bool)
	AppendBools([]bool)

	AppendFloat32(float32)
	AppendFloat32s([]float32)

	AppendFloat64(float64)
	AppendFloat64s([]float64)

	AppendError(error)
	AppendErrors([]error)

	AppendComplex64(complex64)
	AppendComplex64s([]complex64)
	AppendComplex128(complex128)
	AppendComplex128s([]complex128)

	AppendTime(time.Time)
	AppendTimeLayout(time.Time, string)
	AppendTimes([]time.Time)
	AppendTimesLayout([]time.Time, string)
	AppendDuration(time.Duration)
	AppendDurations([]time.Duration)
}

type ArrayMarshaler

type ArrayMarshaler interface {
	MarshalArray(encoder ArrayEncoder) error
}

type Caller

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

func (Caller) Defined

func (c Caller) Defined() bool

func (Caller) File

func (c Caller) File() string

func (Caller) Line

func (c Caller) Line() int

func (Caller) Name

func (c Caller) Name() string

func (Caller) Package

func (c Caller) Package() string

func (Caller) Path

func (c Caller) Path() string

type Config

type Config struct {
	Level            Level                       `json:"level" xml:"level" yaml:"level"`
	IncludeCaller    bool                        `json:"include-caller" xml:"include-caller" yaml:"include-caller"`
	Handlers         Handlers                    `json:"handlers" xml:"handlers" yaml:"handlers"`
	Console          *ConsoleConfig              `json:"console" xml:"console" yaml:"console"`
	File             *FileConfig                 `json:"file" xml:"file" yaml:"file"`
	Syslog           *SyslogConfig               `json:"syslog" xml:"syslog" yaml:"syslog"`
	Package          map[string]*PackageConfig   `json:"package" xml:"package" yaml:"package"`
	ExternalHandlers map[string]ConfigProperties `json:"-" xml:"-" yaml:"-"`
}

type ConfigProperties

type ConfigProperties map[string]any

type ConfigurableHandler

type ConfigurableHandler interface {
	OnConfigure(config Config) error
}

type ConsoleConfig

type ConsoleConfig struct {
	Enabled bool        `json:"enabled" xml:"enabled" yaml:"enabled"`
	Target  Target      `json:"target" xml:"target" yaml:"target"`
	Format  string      `json:"format" xml:"format" yaml:"format"`
	Color   bool        `json:"color" xml:"color" yaml:"color"`
	Level   Level       `json:"level" xml:"level" yaml:"level"`
	Json    *JsonConfig `json:"json" xml:"json" yaml:"json"`
}

type ConsoleHandler

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

func (*ConsoleHandler) AdditionalFields

func (h *ConsoleHandler) AdditionalFields() AdditionalFields

func (*ConsoleHandler) ExcludedKeys

func (h *ConsoleHandler) ExcludedKeys() ExcludedKeys

func (*ConsoleHandler) Format

func (h *ConsoleHandler) Format() string

func (*ConsoleHandler) Handle

func (h *ConsoleHandler) Handle(record Record) error

func (*ConsoleHandler) IsColorEnabled

func (h *ConsoleHandler) IsColorEnabled() bool

func (*ConsoleHandler) IsEnabled

func (h *ConsoleHandler) IsEnabled() bool

func (*ConsoleHandler) IsJsonEnabled

func (h *ConsoleHandler) IsJsonEnabled() bool

func (*ConsoleHandler) IsLoggable

func (h *ConsoleHandler) IsLoggable(record Record) bool

func (*ConsoleHandler) KeyOverrides

func (h *ConsoleHandler) KeyOverrides() KeyOverrides

func (*ConsoleHandler) Level

func (h *ConsoleHandler) Level() Level

func (*ConsoleHandler) OnConfigure

func (h *ConsoleHandler) OnConfigure(config Config) error

func (*ConsoleHandler) SetAdditionalFields

func (h *ConsoleHandler) SetAdditionalFields(additionalFields AdditionalFields)

func (*ConsoleHandler) SetColorEnabled

func (h *ConsoleHandler) SetColorEnabled(enabled bool)

func (*ConsoleHandler) SetEnabled

func (h *ConsoleHandler) SetEnabled(enabled bool)

func (*ConsoleHandler) SetExcludedKeys

func (h *ConsoleHandler) SetExcludedKeys(excludedKeys ExcludedKeys)

func (*ConsoleHandler) SetFormat

func (h *ConsoleHandler) SetFormat(format string)

func (*ConsoleHandler) SetJsonEnabled

func (h *ConsoleHandler) SetJsonEnabled(json bool)

func (*ConsoleHandler) SetKeyOverrides

func (h *ConsoleHandler) SetKeyOverrides(overrides KeyOverrides)

func (*ConsoleHandler) SetLevel

func (h *ConsoleHandler) SetLevel(level Level)

func (*ConsoleHandler) Target

func (h *ConsoleHandler) Target() Target

func (*ConsoleHandler) Writer

func (h *ConsoleHandler) Writer() io.Writer

type ContextFields

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

func ContextFieldsFrom

func ContextFieldsFrom(ctx context.Context) *ContextFields

func NewContextFields

func NewContextFields() *ContextFields

func (*ContextFields) Field

func (cf *ContextFields) Field(name string) (Field, bool)

func (*ContextFields) IsEmpty

func (cf *ContextFields) IsEmpty() bool

func (*ContextFields) Iterator

func (cf *ContextFields) Iterator() *Iterator

type ExcludedKeys

type ExcludedKeys []string

func (*ExcludedKeys) UnmarshalJSON

func (k *ExcludedKeys) UnmarshalJSON(data []byte) error

func (*ExcludedKeys) UnmarshalYAML

func (k *ExcludedKeys) UnmarshalYAML(node *yaml.Node) error

type Facility

type Facility int
const (
	FacilityKernel Facility = iota + 1
	FacilityUserLevel
	FacilityMailSystem
	FacilitySystemDaemons
	FacilitySecurity
	FacilitySyslogd
	FacilityLinePrinter
	FacilityNetworkNews
	FacilityUUCP
	FacilityClockDaemon
	FacilitySecurity2
	FacilityFTPDaemon
	FacilityNTP
	FacilityLogAudit
	FacilityLogAlert
	FacilityClockDaemon2
	FacilityLocalUse0
	FacilityLocalUse1
	FacilityLocalUse2
	FacilityLocalUse3
	FacilityLocalUse4
	FacilityLocalUse5
	FacilityLocalUse6
	FacilityLocalUse7
)

func (*Facility) MarshalJSON

func (f *Facility) MarshalJSON() ([]byte, error)

func (Facility) MarshalYAML

func (f Facility) MarshalYAML() (interface{}, error)

func (*Facility) String

func (f *Facility) String() string

func (*Facility) UnmarshalJSON

func (f *Facility) UnmarshalJSON(data []byte) error

func (*Facility) UnmarshalYAML

func (f *Facility) UnmarshalYAML(node *yaml.Node) error

type Field

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

func (Field) AsJson

func (f Field) AsJson() string

func (Field) Key

func (f Field) Key() string

func (Field) Value

func (f Field) Value() any

func (Field) ValueAsText

func (f Field) ValueAsText() string

type FileConfig

type FileConfig struct {
	Name    string      `json:"name" xml:"name" yaml:"name"`
	Enabled bool        `json:"enabled" xml:"enabled" yaml:"enabled"`
	Path    string      `json:"path" xml:"path" yaml:"path"`
	Format  string      `json:"format" xml:"format" yaml:"format"`
	Level   Level       `json:"level" xml:"level" yaml:"level"`
	Json    *JsonConfig `json:"json" xml:"json" yaml:"json"`
}

type FileHandler

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

func (*FileHandler) AdditionalFields

func (h *FileHandler) AdditionalFields() AdditionalFields

func (*FileHandler) ExcludedKeys

func (h *FileHandler) ExcludedKeys() ExcludedKeys

func (*FileHandler) FileName

func (h *FileHandler) FileName() string

func (*FileHandler) FilePath

func (h *FileHandler) FilePath() string

func (*FileHandler) Format

func (h *FileHandler) Format() string

func (*FileHandler) Handle

func (h *FileHandler) Handle(record Record) error

func (*FileHandler) IsEnabled

func (h *FileHandler) IsEnabled() bool

func (*FileHandler) IsJsonEnabled

func (h *FileHandler) IsJsonEnabled() bool

func (*FileHandler) IsLoggable

func (h *FileHandler) IsLoggable(record Record) bool

func (*FileHandler) KeyOverrides

func (h *FileHandler) KeyOverrides() KeyOverrides

func (*FileHandler) Level

func (h *FileHandler) Level() Level

func (*FileHandler) OnConfigure

func (h *FileHandler) OnConfigure(config Config) error

func (*FileHandler) SetAdditionalFields

func (h *FileHandler) SetAdditionalFields(additionalFields AdditionalFields)

func (*FileHandler) SetEnabled

func (h *FileHandler) SetEnabled(enabled bool)

func (*FileHandler) SetExcludedKeys

func (h *FileHandler) SetExcludedKeys(excludedKeys ExcludedKeys)

func (*FileHandler) SetFormat

func (h *FileHandler) SetFormat(format string)

func (*FileHandler) SetJsonEnabled

func (h *FileHandler) SetJsonEnabled(json bool)

func (*FileHandler) SetKeyOverrides

func (h *FileHandler) SetKeyOverrides(overrides KeyOverrides)

func (*FileHandler) SetLevel

func (h *FileHandler) SetLevel(level Level)

func (*FileHandler) Writer

func (h *FileHandler) Writer() io.Writer

type Handler

type Handler interface {
	Handle(record Record) error
	SetLevel(level Level)
	Level() Level
	SetEnabled(enabled bool)
	IsEnabled() bool
	IsLoggable(record Record) bool
	Writer() io.Writer
}

func GetHandler

func GetHandler(name string) (Handler, bool)

type Handlers

type Handlers []string

func (*Handlers) UnmarshalJSON

func (h *Handlers) UnmarshalJSON(data []byte) error

func (*Handlers) UnmarshalYAML

func (h *Handlers) UnmarshalYAML(node *yaml.Node) error

type Iterator

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

func Values

func Values(ctx context.Context) *Iterator

func (*Iterator) HasNext

func (i *Iterator) HasNext() bool

func (*Iterator) Next

func (i *Iterator) Next() (Field, bool)

type JsonConfig

type JsonConfig struct {
	Enabled          bool             `json:"enabled" xml:"enabled" yaml:"enabled"`
	ExcludedKeys     ExcludedKeys     `json:"excluded-keys" xml:"excluded-keys" yaml:"excluded-keys"`
	KeyOverrides     KeyOverrides     `json:"key-overrides" xml:"key-overrides" yaml:"key-overrides"`
	AdditionalFields AdditionalFields `json:"additional-fields" xml:"additional-fields" yaml:"additional-fields"`
}

type KeyOverrides

type KeyOverrides map[string]string

type Level

type Level int
const (
	LevelOff Level = iota + 1
	LevelError
	LevelWarn
	LevelInfo
	LevelDebug
	LevelTrace
	LevelAll
)

func (*Level) MarshalJSON

func (l *Level) MarshalJSON() ([]byte, error)

func (Level) MarshalYAML

func (l Level) MarshalYAML() (interface{}, error)

func (Level) String

func (l Level) String() string

func (*Level) UnmarshalJSON

func (l *Level) UnmarshalJSON(data []byte) error

func (*Level) UnmarshalYAML

func (l *Level) UnmarshalYAML(node *yaml.Node) error

type Logger

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

func Get

func Get() *Logger

func Named

func Named(name string) *Logger

func Of

func Of[T any]() *Logger

func (*Logger) D

func (l *Logger) D(ctx context.Context, msg string, args ...any)

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any)

func (*Logger) E

func (l *Logger) E(ctx context.Context, msg string, args ...any)

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any)

func (*Logger) I

func (l *Logger) I(ctx context.Context, msg string, args ...any)

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any)

func (*Logger) IsDebugEnabled

func (l *Logger) IsDebugEnabled() bool

func (*Logger) IsErrorEnabled

func (l *Logger) IsErrorEnabled() bool

func (*Logger) IsInfoEnabled

func (l *Logger) IsInfoEnabled() bool

func (*Logger) IsLoggable

func (l *Logger) IsLoggable(level Level) bool

func (*Logger) IsTraceEnabled

func (l *Logger) IsTraceEnabled() bool

func (*Logger) IsWarnEnabled

func (l *Logger) IsWarnEnabled() bool

func (*Logger) Level

func (l *Logger) Level() Level

func (*Logger) Name

func (l *Logger) Name() string

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

func (*Logger) T

func (l *Logger) T(ctx context.Context, msg string, args ...any)

func (*Logger) Trace

func (l *Logger) Trace(msg string, args ...any)

func (*Logger) W

func (l *Logger) W(ctx context.Context, msg string, args ...any)

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any)

type ObjectEncoder

type ObjectEncoder interface {
	AddAny(key string, val any) error
	AddObject(key string, marshaler ObjectMarshaler) error
	AddArray(key string, marshaler ArrayMarshaler) error

	AddString(key, value string)
	AddStrings(key string, arr []string)

	AddByteString(key string, arr []byte)

	AddInt(key string, value int)
	AddInts(key string, arr []int)

	AddInt8(key string, value int8)
	AddInt8s(key string, arr []int8)

	AddInt16(key string, value int16)
	AddInt16s(key string, arr []int16)

	AddInt32(key string, value int32)
	AddInt32s(key string, arr []int32)

	AddInt64(key string, value int64)
	AddInt64s(key string, arr []int64)

	AddUint(key string, value uint)
	AddUints(k string, v []uint)

	AddUint8(key string, value uint8)
	AddUint8s(k string, v []uint8)

	AddUint16(key string, value uint16)
	AddUint16s(k string, v []uint16)

	AddUint32(key string, value uint32)
	AddUint32s(k string, v []uint32)

	AddUint64(key string, value uint64)
	AddUint64s(k string, v []uint64)

	AddUintptr(key string, value uintptr)
	AddUintptrs(key string, arr []uintptr)

	AddBool(key string, value bool)
	AddBools(key string, value []bool)

	AddFloat32(key string, value float32)
	AddFloat32s(key string, val []float32)

	AddFloat64(key string, value float64)
	AddFloat64s(key string, val []float64)

	AddError(key string, val error)
	AddErrors(key string, val []error)

	AddTime(key string, value time.Time)
	AddTimeLayout(key string, value time.Time, layout string)
	AddTimes(key string, val []time.Time)
	AddTimesLayout(key string, val []time.Time, layout string)

	AddDuration(key string, value time.Duration)
	AddDurations(key string, val []time.Duration)

	AddComplex64(key string, value complex64)
	AddComplex64s(key string, val []complex64)

	AddComplex128(key string, value complex128)
	AddComplex128s(key string, val []complex128)

	OpenNamespace(key string)
	CloseNamespace()
	CloseOpenNamespaces()
}

type ObjectMarshaler

type ObjectMarshaler interface {
	MarshalObject(encoder ObjectEncoder) error
}

type PackageConfig

type PackageConfig struct {
	Level             Level    `json:"level" xml:"level" yaml:"level"`
	UseParentHandlers bool     `json:"use-parent-handlers" xml:"use-parent-handlers" yaml:"use-parent-handlers"`
	Handlers          Handlers `json:"handlers" xml:"handlers" yaml:"handlers"`
}

type Protocol

type Protocol string
const (
	ProtocolTCP Protocol = "tcp"
	ProtocolUDP Protocol = "udp"
)

func (*Protocol) MarshalJSON

func (p *Protocol) MarshalJSON() ([]byte, error)

func (Protocol) MarshalYAML

func (p Protocol) MarshalYAML() (interface{}, error)

func (*Protocol) String

func (p *Protocol) String() string

func (*Protocol) UnmarshalJSON

func (p *Protocol) UnmarshalJSON(data []byte) error

func (*Protocol) UnmarshalYAML

func (p *Protocol) UnmarshalYAML(node *yaml.Node) error

type Record

type Record struct {
	Time       time.Time
	Level      Level
	Message    string
	Context    context.Context
	LoggerName string
	StackTrace string
	Error      error
	Caller     Caller
}

type SysLogType

type SysLogType int
const (
	RFC5424 SysLogType = iota + 1
	RFC3164
)

func (*SysLogType) MarshalJSON

func (t *SysLogType) MarshalJSON() ([]byte, error)

func (SysLogType) MarshalYAML

func (t SysLogType) MarshalYAML() (interface{}, error)

func (*SysLogType) String

func (t *SysLogType) String() string

func (*SysLogType) UnmarshalJSON

func (t *SysLogType) UnmarshalJSON(data []byte) error

func (*SysLogType) UnmarshalYAML

func (t *SysLogType) UnmarshalYAML(node *yaml.Node) error

type SyslogConfig

type SyslogConfig struct {
	Enabled          bool       `json:"enabled" xml:"enabled" yaml:"enabled"`
	Endpoint         string     `json:"endpoint" xml:"endpoint" yaml:"endpoint"`
	AppName          string     `json:"app-name" xml:"app-name" yaml:"app-name"`
	Hostname         string     `json:"hostname" xml:"hostname" yaml:"hostname"`
	Facility         Facility   `json:"facility" xml:"facility" yaml:"facility"`
	LogType          SysLogType `json:"log-type" xml:"log-type" yaml:"log-type"`
	Protocol         Protocol   `json:"protocol" xml:"protocol" yaml:"protocol"`
	Format           string     `json:"format" xml:"format" yaml:"format"`
	Level            Level      `json:"level" xml:"level" yaml:"level"`
	BlockOnReconnect bool       `json:"block-on-reconnect" xml:"block-on-reconnect" yaml:"block-on-reconnect"`
}

type SyslogHandler

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

func (*SyslogHandler) ApplicationName

func (h *SyslogHandler) ApplicationName() string

func (*SyslogHandler) Endpoint

func (h *SyslogHandler) Endpoint() string

func (*SyslogHandler) Facility

func (h *SyslogHandler) Facility() Facility

func (*SyslogHandler) Format

func (h *SyslogHandler) Format() string

func (*SyslogHandler) Handle

func (h *SyslogHandler) Handle(record Record) error

func (*SyslogHandler) Hostname

func (h *SyslogHandler) Hostname() string

func (*SyslogHandler) IsBlockOnReconnect

func (h *SyslogHandler) IsBlockOnReconnect() bool

func (*SyslogHandler) IsEnabled

func (h *SyslogHandler) IsEnabled() bool

func (*SyslogHandler) IsLoggable

func (h *SyslogHandler) IsLoggable(record Record) bool

func (*SyslogHandler) Level

func (h *SyslogHandler) Level() Level

func (*SyslogHandler) LogType

func (h *SyslogHandler) LogType() SysLogType

func (*SyslogHandler) OnConfigure

func (h *SyslogHandler) OnConfigure(config Config) error

func (*SyslogHandler) Protocol

func (h *SyslogHandler) Protocol() Protocol

func (*SyslogHandler) SetApplicationName

func (h *SyslogHandler) SetApplicationName(name string)

func (*SyslogHandler) SetEnabled

func (h *SyslogHandler) SetEnabled(enabled bool)

func (*SyslogHandler) SetFacility

func (h *SyslogHandler) SetFacility(facility Facility)

func (*SyslogHandler) SetFormat

func (h *SyslogHandler) SetFormat(format string)

func (*SyslogHandler) SetHostname

func (h *SyslogHandler) SetHostname(hostname string)

func (*SyslogHandler) SetLevel

func (h *SyslogHandler) SetLevel(level Level)

func (*SyslogHandler) Writer

func (h *SyslogHandler) Writer() io.Writer

type Target

type Target int
const (
	TargetStderr Target = iota + 1
	TargetStdout
	TargetDiscard
)

func (*Target) MarshalJSON

func (t *Target) MarshalJSON() ([]byte, error)

func (Target) MarshalYAML

func (t Target) MarshalYAML() (interface{}, error)

func (*Target) String

func (t *Target) String() string

func (*Target) UnmarshalJSON

func (t *Target) UnmarshalJSON(data []byte) error

func (*Target) UnmarshalYAML

func (t *Target) UnmarshalYAML(node *yaml.Node) error

Jump to

Keyboard shortcuts

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