log

package
v0.0.0-...-495e01f Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2023 License: Apache-2.0 Imports: 20 Imported by: 0

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

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

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

func EventFormatTextMessage

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

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

func HasEventWriter(writerType string) bool

func Info

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

func IsDebug

func IsDebug() bool

func IsLoggerEnabled

func IsLoggerEnabled(name string) bool

func IsTrace

func IsTrace() bool

func Log

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

func LoggerToWriter

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

LoggerToWriter wraps a log function to an io.Writer

func RegisterEventWriter

func RegisterEventWriter(writerType string, p EventWriterProvider)

func SetConsoleLogger

func SetConsoleLogger(loggerName, writerName string, level Level)

func Stack

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

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

BaseLogger provides the basic logging functions

type ColorAttribute

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

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

func ColoredMethod

func ColoredMethod(method string) *ColoredValue

ColoredMethod adds colors for HTTP methods on log

func ColoredStatus

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

ColoredStatus adds colors for HTTP status

func ColoredTime

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

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

func (*ColoredValue) Format

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

type Event

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

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

type EventFormatter

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

type EventWriter

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

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

func NewEventWriterConn

func NewEventWriterConn(writerName string, writerMode WriterMode) EventWriter

func NewEventWriterConsole

func NewEventWriterConsole(name string, mode WriterMode) EventWriter

func NewEventWriterFile

func NewEventWriterFile(name string, mode WriterMode) EventWriter

type EventWriterBase

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

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

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

func (*EventWriterBaseImpl) Base

func (*EventWriterBaseImpl) GetLevel

func (b *EventWriterBaseImpl) GetLevel() Level

func (*EventWriterBaseImpl) GetWriterName

func (b *EventWriterBaseImpl) GetWriterName() string

func (*EventWriterBaseImpl) GetWriterType

func (b *EventWriterBaseImpl) GetWriterType() string

func (*EventWriterBaseImpl) Run

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

Run is the default implementation for EventWriter.Run

type EventWriterProvider

type EventWriterProvider func(writerName string, writerMode WriterMode) EventWriter

EventWriterProvider is the function for creating a new EventWriter

type Flags

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

func FlagsFromBits

func FlagsFromBits(flags uint32) Flags

func FlagsFromString

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

func (Flags) Bits

func (f Flags) Bits() uint32

func (Flags) MarshalJSON

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

func (Flags) String

func (f Flags) String() string

func (*Flags) UnmarshalJSON

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

type Level

type Level int

Level is the level of the logger

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

func GetLevel

func GetLevel() Level

func LevelFromString

func LevelFromString(level string) Level

LevelFromString takes a level string and returns a Level

func (Level) ColorAttributes

func (l Level) ColorAttributes() []ColorAttribute

func (Level) MarshalJSON

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

MarshalJSON takes a Level and turns it into text

func (Level) String

func (l Level) String() string

func (*Level) UnmarshalJSON

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

UnmarshalJSON takes text and turns it into a Level

type LevelLogger

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

type LogStringer interface {
	LogString() string
}

type Logger

type Logger interface {
	BaseLogger
	LevelLogger
}

func BaseLoggerToGeneralLogger

func BaseLoggerToGeneralLogger(b BaseLogger) Logger

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

func GetLogger

func GetLogger(name string) Logger

type LoggerImpl

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

func NewLoggerWithWriters

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

func (*LoggerImpl) AddWriters

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

func (l *LoggerImpl) Close()

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

func (*LoggerImpl) DumpWriters

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

func (l *LoggerImpl) GetLevel() Level

func (*LoggerImpl) IsEnabled

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

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

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

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

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

func (*LoggerImpl) SendLogEvent

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

SendLogEvent sends a log event to all writers

type LoggerManager

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

LoggerManager manages loggers and shared event writers

func GetManager

func GetManager() *LoggerManager

func NewManager

func NewManager() *LoggerManager

func (*LoggerManager) Close

func (m *LoggerManager) Close()

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

func (*LoggerManager) DumpLoggers

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

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

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

GetPauseChan returns a channel for writer pausing

func (*LoggerManager) GetSharedWriter

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

func (*LoggerManager) NewSharedWriter

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

func (m *LoggerManager) PauseAll()

PauseAll pauses all event writers

func (*LoggerManager) ResumeAll

func (m *LoggerManager) ResumeAll()

ResumeAll resumes all event writers

type PrintfLogger

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

func (*PrintfLogger) Printf

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

type WriterConnOption

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

type WriterConsoleOption

type WriterConsoleOption struct {
	Stderr bool
}

type WriterFileOption

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

type WriterMode

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