log

package
v1.21.10 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: MIT Imports: 21 Imported by: 1,966

Documentation

Overview

Package log provides logging capabilities for Gitea. Concepts:

* Logger: a Logger provides logging functions and dispatches log events to all its writers

* EventWriter: written log Event to a destination (eg: file, console)

  • EventWriterBase: the base struct of a writer, it contains common fields and functions for all writers
  • WriterType: the type name of a writer, eg: console, file
  • WriterName: aka Mode Name in document, the name of a writer instance, it's usually defined by the config file. It is called "mode name" because old code use MODE as config key, to keep compatibility, keep this concept.

* WriterMode: the common options for all writers, eg: log level.

  • WriterConsoleOption and others: the specified options for a writer, eg: file path, remote address.

Call graph: -> log.Info() -> LoggerImpl.Log() -> LoggerImpl.SendLogEvent, then the event goes into writer's goroutines -> EventWriter.Run() handles the events

Index

Constants

View Source
const (
	Ldate          uint32 = 1 << iota // the date in the local time zone: 2009/01/23
	Ltime                             // the time in the local time zone: 01:23:23
	Lmicroseconds                     // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                         // full file name and line number: /a/logger/c/d.go:23
	Lshortfile                        // final file name element and line number: d.go:23. overrides Llongfile
	Lfuncname                         // function name of the caller: runtime.Caller()
	Lshortfuncname                    // last part of the function name
	LUTC                              // if Ldate or Ltime is set, use UTC rather than the local time zone
	Llevelinitial                     // Initial character of the provided level in brackets, eg. [I] for info
	Llevel                            // Provided level in brackets [INFO]
	Lgopid                            // the Goroutine-PID of the context

	Lmedfile  = Lshortfile | Llongfile                                    // last 20 characters of the filename
	LstdFlags = Ldate | Ltime | Lmedfile | Lshortfuncname | Llevelinitial // default
)

These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed. There is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only if more than time is stated is specified. For example, flags Ldate | Ltime produce, 2009/01/23 01:23:23 message. The standard is: 2009/01/23 01:23:23 ...a/logger/c/d.go:23:runtime.Caller() [I]: message

View Source
const CRITICAL = ERROR // most logger frameworks doesn't support CRITICAL, and it doesn't seem useful
View Source
const DEFAULT = "default"
View Source
const Ldefault = LstdFlags

Variables

View Source
var CanColorStderr = true

CanColorStderr reports if we can color the Stderr

View Source
var CanColorStdout = true

CanColorStdout reports if we can color the Stdout Although we could do terminal sniffing and the like - in reality most tools on *nix are happy to display ansi colors. We will terminal sniff on Windows in console_windows.go

Functions

func ColorBytes added in v1.9.0

func ColorBytes(attrs ...ColorAttribute) []byte

ColorBytes converts a list of ColorAttributes to a byte array

func Critical

func Critical(format string, v ...any)

func Debug

func Debug(format string, v ...any)

func Error

func Error(format string, v ...any)

func ErrorWithSkip added in v1.9.0

func ErrorWithSkip(skip int, format string, v ...any)

func EventFormatTextMessage added in v1.20.0

func EventFormatTextMessage(mode *WriterMode, event *Event, msgFormat string, msgArgs ...any) []byte

EventFormatTextMessage makes the log message for a writer with its mode. This function is a copy of the original package

func FallbackErrorf added in v1.20.0

func FallbackErrorf(format string, args ...any)

FallbackErrorf is the last chance to show an error if the logger has internal errors

func Fatal

func Fatal(format string, v ...any)

Fatal records fatal log and exit process

func HasEventWriter added in v1.20.0

func HasEventWriter(writerType string) bool

func Info

func Info(format string, v ...any)

func IsDebug added in v1.9.0

func IsDebug() bool

func IsLoggerEnabled added in v1.20.0

func IsLoggerEnabled(name string) bool

func IsTrace added in v1.9.0

func IsTrace() bool

func Log added in v1.9.0

func Log(skip int, level Level, format string, v ...any)

func LoggerToWriter added in v1.20.0

func LoggerToWriter(logf func(format string, args ...any)) io.Writer

LoggerToWriter wraps a log function to an io.Writer

func RegisterEventWriter added in v1.20.0

func RegisterEventWriter(writerType string, p EventWriterProvider)

func SetConsoleLogger added in v1.20.0

func SetConsoleLogger(loggerName, writerName string, level Level)

func Stack added in v1.9.0

func Stack(skip int) string

Stack will skip back the provided number of frames and return a stack trace with source code. Although we could just use debug.Stack(), this routine will return the source code and skip back the provided number of frames - i.e. allowing us to ignore preceding function calls. A skip of 0 returns the stack trace for the calling function, not including this call. If the problem is a lack of memory of course all this is not going to work...

func Trace

func Trace(format string, v ...any)

func Warn

func Warn(format string, v ...any)

Types

type BaseLogger added in v1.20.0

type BaseLogger interface {
	Log(skip int, level Level, format string, v ...any)
	GetLevel() Level
}

BaseLogger provides the basic logging functions

type ColorAttribute added in v1.9.0

type ColorAttribute int

ColorAttribute defines a single SGR Code

const (
	Reset ColorAttribute = iota
	Bold
	Faint
	Italic
	Underline
	BlinkSlow
	BlinkRapid
	ReverseVideo
	Concealed
	CrossedOut
)

Base ColorAttributes

const (
	FgBlack ColorAttribute = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta
	FgCyan
	FgWhite
)

Foreground text colors

const (
	FgHiBlack ColorAttribute = iota + 90
	FgHiRed
	FgHiGreen
	FgHiYellow
	FgHiBlue
	FgHiMagenta
	FgHiCyan
	FgHiWhite
)

Foreground Hi-Intensity text colors

const (
	BgBlack ColorAttribute = iota + 40
	BgRed
	BgGreen
	BgYellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
)

Background text colors

const (
	BgHiBlack ColorAttribute = iota + 100
	BgHiRed
	BgHiGreen
	BgHiYellow
	BgHiBlue
	BgHiMagenta
	BgHiCyan
	BgHiWhite
)

Background Hi-Intensity text colors

type ColoredValue added in v1.9.0

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

func ColoredMethod added in v1.9.0

func ColoredMethod(method string) *ColoredValue

ColoredMethod adds colors for HTTP methods on log

func ColoredStatus added in v1.9.0

func ColoredStatus(status int, s ...string) *ColoredValue

ColoredStatus adds colors for HTTP status

func ColoredTime added in v1.9.0

func ColoredTime(duration time.Duration) *ColoredValue

ColoredTime converts the provided time to a ColoredValue for logging. The duration is always formatted in milliseconds.

func NewColoredValue added in v1.9.0

func NewColoredValue(v any, color ...ColorAttribute) *ColoredValue

func (*ColoredValue) Format added in v1.9.0

func (c *ColoredValue) Format(f fmt.State, verb rune)

type Event added in v1.9.0

type Event struct {
	Time time.Time

	GoroutinePid string
	Caller       string
	Filename     string
	Line         int

	Level Level

	MsgSimpleText string

	Stacktrace string
	// contains filtered or unexported fields
}

type EventFormatted added in v1.20.0

type EventFormatted struct {
	Origin *Event
	Msg    any // the message formatted by the writer's formatter, the writer knows its type
}

type EventFormatter added in v1.20.0

type EventFormatter func(mode *WriterMode, event *Event, msgFormat string, msgArgs ...any) []byte

type EventWriter added in v1.20.0

type EventWriter interface {
	EventWriterBase
}

EventWriter is the general interface for all event writers EventWriterBase is only used as its base interface A writer implementation could override the default EventWriterBase functions eg: a writer can override the Run to handle events in its own way with its own goroutine

func NewEventWriter added in v1.20.0

func NewEventWriter(name, writerType string, mode WriterMode) (EventWriter, error)

func NewEventWriterConn added in v1.20.0

func NewEventWriterConn(writerName string, writerMode WriterMode) EventWriter

func NewEventWriterConsole added in v1.20.0

func NewEventWriterConsole(name string, mode WriterMode) EventWriter

func NewEventWriterFile added in v1.20.0

func NewEventWriterFile(name string, mode WriterMode) EventWriter

type EventWriterBase added in v1.20.0

type EventWriterBase interface {
	Base() *EventWriterBaseImpl
	GetWriterType() string
	GetWriterName() string
	GetLevel() Level

	Run(ctx context.Context)
}

EventWriterBase is the base interface for most event writers It provides default implementations for most methods

type EventWriterBaseImpl added in v1.20.0

type EventWriterBaseImpl struct {
	Name  string
	Mode  *WriterMode
	Queue chan *EventFormatted

	FormatMessage     EventFormatter // format the Event to a message and write it to output
	OutputWriteCloser io.WriteCloser // it will be closed when the event writer is stopped
	GetPauseChan      func() chan struct{}
	// contains filtered or unexported fields
}

func NewEventWriterBase added in v1.20.0

func NewEventWriterBase(name, writerType string, mode WriterMode) *EventWriterBaseImpl

func (*EventWriterBaseImpl) Base added in v1.20.0

func (*EventWriterBaseImpl) GetLevel added in v1.20.0

func (b *EventWriterBaseImpl) GetLevel() Level

func (*EventWriterBaseImpl) GetWriterName added in v1.20.0

func (b *EventWriterBaseImpl) GetWriterName() string

func (*EventWriterBaseImpl) GetWriterType added in v1.20.0

func (b *EventWriterBaseImpl) GetWriterType() string

func (*EventWriterBaseImpl) Run added in v1.20.0

func (b *EventWriterBaseImpl) Run(ctx context.Context)

Run is the default implementation for EventWriter.Run

type EventWriterProvider added in v1.20.0

type EventWriterProvider func(writerName string, writerMode WriterMode) EventWriter

EventWriterProvider is the function for creating a new EventWriter

type Flags added in v1.20.0

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

func FlagsFromBits added in v1.20.0

func FlagsFromBits(flags uint32) Flags

func FlagsFromString added in v1.9.0

func FlagsFromString(from string, def ...uint32) Flags

func (Flags) Bits added in v1.20.0

func (f Flags) Bits() uint32

func (Flags) MarshalJSON added in v1.20.0

func (f Flags) MarshalJSON() ([]byte, error)

func (Flags) String added in v1.20.0

func (f Flags) String() string

func (*Flags) UnmarshalJSON added in v1.20.0

func (f *Flags) UnmarshalJSON(bytes []byte) error

type Level added in v1.9.0

type Level int

Level is the level of the logger

const (
	UNDEFINED Level = iota
	TRACE
	DEBUG
	INFO
	WARN
	ERROR
	FATAL
	NONE
)

func GetLevel added in v1.9.0

func GetLevel() Level

func LevelFromString added in v1.20.0

func LevelFromString(level string) Level

LevelFromString takes a level string and returns a Level

func (Level) ColorAttributes added in v1.20.0

func (l Level) ColorAttributes() []ColorAttribute

func (Level) MarshalJSON added in v1.9.0

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

MarshalJSON takes a Level and turns it into text

func (Level) String added in v1.9.0

func (l Level) String() string

func (*Level) UnmarshalJSON added in v1.9.0

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

UnmarshalJSON takes text and turns it into a Level

type LevelLogger added in v1.14.0

type LevelLogger interface {
	LevelEnabled(level Level) bool

	Trace(format string, v ...any)
	Debug(format string, v ...any)
	Info(format string, v ...any)
	Warn(format string, v ...any)
	Error(format string, v ...any)
	Critical(format string, v ...any)
}

LevelLogger provides level-related logging functions

type LogStringer added in v1.20.0

type LogStringer interface {
	LogString() string
}

type Logger

type Logger interface {
	BaseLogger
	LevelLogger
}

func BaseLoggerToGeneralLogger added in v1.20.0

func BaseLoggerToGeneralLogger(b BaseLogger) Logger

BaseLoggerToGeneralLogger wraps a BaseLogger (which only has Log() function) to a Logger (which has Info() function)

func GetLogger added in v1.9.0

func GetLogger(name string) Logger

type LoggerImpl added in v1.20.0

type LoggerImpl struct {
	LevelLogger
	// contains filtered or unexported fields
}

func NewLoggerWithWriters added in v1.20.0

func NewLoggerWithWriters(ctx context.Context, name string, writer ...EventWriter) *LoggerImpl

func (*LoggerImpl) AddWriters added in v1.20.0

func (l *LoggerImpl) AddWriters(writer ...EventWriter)

AddWriters adds writers to the logger, and starts them. Existing writers will be replaced by new ones.

func (*LoggerImpl) Close added in v1.20.0

func (l *LoggerImpl) Close()

Close closes the logger, non-shared writers are closed and flushed

func (*LoggerImpl) DumpWriters added in v1.20.0

func (l *LoggerImpl) DumpWriters() map[string]any

DumpWriters dumps the writers as a JSON map, it's used for debugging and display purposes.

func (*LoggerImpl) GetLevel added in v1.20.0

func (l *LoggerImpl) GetLevel() Level

func (*LoggerImpl) IsEnabled added in v1.20.0

func (l *LoggerImpl) IsEnabled() bool

IsEnabled returns true if the logger is enabled: it has a working level and has writers Fatal is not considered as enabled, because it's a special case and the process just exits

func (*LoggerImpl) Log added in v1.20.0

func (l *LoggerImpl) Log(skip int, level Level, format string, logArgs ...any)

Log prepares the log event, if the level matches, the event will be sent to the writers

func (*LoggerImpl) RemoveWriter added in v1.20.0

func (l *LoggerImpl) RemoveWriter(modeName string) error

RemoveWriter removes a writer from the logger, and the writer is closed and flushed if it is not shared

func (*LoggerImpl) ReplaceAllWriters added in v1.20.0

func (l *LoggerImpl) ReplaceAllWriters(writer ...EventWriter)

ReplaceAllWriters replaces all writers from the logger, non-shared writers are closed and flushed

func (*LoggerImpl) SendLogEvent added in v1.20.0

func (l *LoggerImpl) SendLogEvent(event *Event)

SendLogEvent sends a log event to all writers

type LoggerManager added in v1.20.0

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

LoggerManager manages loggers and shared event writers

func GetManager added in v1.20.0

func GetManager() *LoggerManager

func NewManager added in v1.20.0

func NewManager() *LoggerManager

func (*LoggerManager) Close added in v1.20.0

func (m *LoggerManager) Close()

Close closes the logger manager, all loggers and writers will be closed, the messages are flushed.

func (*LoggerManager) DumpLoggers added in v1.20.0

func (m *LoggerManager) DumpLoggers() map[string]any

DumpLoggers returns a map of all loggers and their event writers, for debugging and display purposes.

func (*LoggerManager) GetLogger added in v1.20.0

func (m *LoggerManager) GetLogger(name string) *LoggerImpl

GetLogger returns a logger with the given name. If the logger doesn't exist, a new empty one will be created.

func (*LoggerManager) GetPauseChan added in v1.20.0

func (m *LoggerManager) GetPauseChan() chan struct{}

GetPauseChan returns a channel for writer pausing

func (*LoggerManager) GetSharedWriter added in v1.20.0

func (m *LoggerManager) GetSharedWriter(writerName string) EventWriter

func (*LoggerManager) NewSharedWriter added in v1.20.0

func (m *LoggerManager) NewSharedWriter(writerName, writerType string, mode WriterMode) (writer EventWriter, err error)

NewSharedWriter creates a new shared event writer, it can be used by multiple loggers, and a shared writer won't be closed if a logger is closed.

func (*LoggerManager) PauseAll added in v1.20.0

func (m *LoggerManager) PauseAll()

PauseAll pauses all event writers

func (*LoggerManager) ResumeAll added in v1.20.0

func (m *LoggerManager) ResumeAll()

ResumeAll resumes all event writers

type PrintfLogger added in v1.20.0

type PrintfLogger struct {
	Logf func(format string, args ...any)
}

func (*PrintfLogger) Printf added in v1.20.0

func (p *PrintfLogger) Printf(format string, args ...any)

type WriterConnOption added in v1.20.0

type WriterConnOption struct {
	Addr           string
	Protocol       string
	Reconnect      bool
	ReconnectOnMsg bool
}

type WriterConsoleOption added in v1.20.0

type WriterConsoleOption struct {
	Stderr bool
}

type WriterFileOption added in v1.20.0

type WriterFileOption struct {
	FileName         string
	MaxSize          int64
	LogRotate        bool
	DailyRotate      bool
	MaxDays          int
	Compress         bool
	CompressionLevel int
}

type WriterMode added in v1.20.0

type WriterMode struct {
	BufferLen int

	Level    Level
	Prefix   string
	Colorize bool
	Flags    Flags

	Expression string

	StacktraceLevel Level

	WriterOption any
}

WriterMode is the mode for creating a new EventWriter, it contains common options for all writers Its WriterOption field is the specified options for a writer, it should be passed by value but not by pointer

Jump to

Keyboard shortcuts

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