log

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2019 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrorText can modify the prefix that will be prepended
	// to the output message log when `Error/Errorf` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[ERRO]" and pio.Red("[ERRO]").
	//
	// Deprecated Use `Levels[ErrorLevel].SetText(string, string)` instead.
	ErrorText = Levels[ErrorLevel].SetText

	// WarnText can modify the prefix that will be prepended
	// to the output message log when `Warn/Warnf` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[WARN]" and pio.Purple("[WARN]").
	//
	// Deprecated Use `Levels[WarnLevel].SetText(string, string)` instead.
	WarnText = Levels[WarnLevel].SetText

	// InfoText can modify the prefix that will be prepended
	// to the output message log when `Info/Infof` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[INFO]" and pio.LightGreen("[INFO]").
	//
	// Deprecated Use `Levels[InfoLevel].SetText(string, string)` instead.
	InfoText = Levels[InfoLevel].SetText

	// DebugText can modify the prefix that will be prepended
	// to the output message log when `Info/Infof` functions are being used.
	//
	// If "newColorfulText" is empty then it will update the text color version using
	// the default values by using the new raw text.
	//
	// Defaults to "[DBUG]" and pio.Yellow("[DBUG]").
	//
	// Deprecated Use `Levels[DebugLevel].SetText(string, string)` instead.
	DebugText = Levels[DebugLevel].SetText

	// GetTextForLevel is the function which
	// has the "final" responsibility to generate the text (colorful or not)
	// that is prepended to the leveled log message
	// when `Error/Errorf, Warn/Warnf, Info/Infof or Debug/Debugf`
	// functions are being called.
	//
	// It can be used to override the default behavior, at the start-up state.
	GetTextForLevel = func(level Level, enableColor bool) string {
		if meta, ok := Levels[level]; ok {
			return meta.Text(enableColor)
		}
		return ""
	}
)
View Source
var Levels = map[Level]*LevelMetadata{
	DisableLevel: {
		Name:             "disable",
		AlternativeNames: []string{"disabled"},
		RawText:          "",
		ColorfulText:     "",
	},
	FatalLevel: {
		Name:    "fatal",
		RawText: "[FTAL]",

		ColorfulText: pio.RedBackground("[FTAL]"),
	},
	ErrorLevel: {
		Name:         "error",
		RawText:      "[ERRO]",
		ColorfulText: pio.Red("[ERRO]"),
	},
	WarnLevel: {
		Name:             "warn",
		AlternativeNames: []string{"warning"},
		RawText:          "[WARN]",
		ColorfulText:     pio.Purple("[WARN]"),
	},
	InfoLevel: {
		Name:         "info",
		RawText:      "[INFO]",
		ColorfulText: pio.LightGreen("[INFO]"),
	},
	DebugLevel: {
		Name:         "debug",
		RawText:      "[DBUG]",
		ColorfulText: pio.Yellow("[DBUG]"),
	},
}

Levels contains the levels and their mapped (pointer of, in order to be able to be modified) metadata, callers are allowed to modify this package-level global variable without any loses.

View Source
var Local = clockFn(time.Now)

Local is an object satisfying the Clock interface, which returns the current time in the local timezone

View Source
var NopOutput = pio.NopOutput()

NopOutput disables the output.

View Source
var UTC = clockFn(func() time.Time { return time.Now().UTC() })

UTC is an object satisfying the Clock interface, which returns the current time in UTC

Functions

func TipInDevelopment added in v0.0.5

func TipInDevelopment(msg string)

TipInDevelopment 提供在开发模式下提示开发人员处理的信息

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock is the interface used by the RotateLogs object to determine the current time

type Level

type Level uint32

Level is a number which defines the log level.

const (
	// DisableLevel will disable the printer.
	DisableLevel Level = iota
	// FatalLevel will `os.Exit(1)` no matter the level of the logger.
	// If the logger's level is fatal, error, warn, info or debug
	// then it will print the log message too.
	FatalLevel
	// ErrorLevel will print only errors.
	ErrorLevel
	// WarnLevel will print errors and warnings.
	WarnLevel
	// InfoLevel will print errors, warnings and infos.
	InfoLevel
	// DebugLevel will print on any level, fatals, errors, warnings, infos and debug logs.
	DebugLevel
)

The available built'n log levels, users can add or modify a level via `Levels` field.

func ParseLevel

func ParseLevel(levelName string) Level

ParseLevel returns a `golog.Level` from a string level. Note that all existing log levels (name, prefix and color) can be customized and new one can be added by the package-level `golog.Levels` map variable.

type LevelMetadata

type LevelMetadata struct {
	// The Name of the Level
	// that named (lowercased) will be used
	// to convert a string level on `SetLevel`
	// to the correct Level type.
	Name string
	// AlternativeNames are the names that can be referred to this specific log level.
	// i.e Name = "warn"
	// AlternativeNames = []string{"warning"}, it's an optional field,
	// therefore we keep Name as a simple string and created this new field.
	AlternativeNames []string
	// Tha RawText will be the prefix of the log level
	// when output doesn't supports colors.
	//
	// When RawText is changed its ColorfulText is also changed
	// to a default color, but callers are able to change it too.
	RawText string
	// The ColorfulText will be the prefix of the log level
	// when output supports colors, almost everything except
	// os files and putty-based terminals(?).
	//
	// If ColorfulText is empty then built'n colors
	// are being used to wrap the "RawText".
	ColorfulText string
}

LevelMetadata describes the information behind a log Level, each level has its own unique metadata.

func (*LevelMetadata) SetText

func (m *LevelMetadata) SetText(newRawText string, newColorfulText string)

SetText can modify the prefix that will be prepended to the output message log when `Error/Errorf` functions are being used.

If "newRawText" is empty then it will just skip the Text set-ing. If "newColorfulText" is empty then it will update the text color version using the default values by using the new raw text.

func (*LevelMetadata) Text

func (m *LevelMetadata) Text(enableColor bool) string

Text returns the text that should be prepended to the log message when a specific log level is being written.

type Log

type Log struct {
	// Logger is the original printer of this Log.
	Logger *Logger
	// Time is the current time
	Time time.Time
	// Level is the log level.
	Level Level
	// Message is the string reprensetation of the log's main body.
	Message string
	// NewLine returns false if this Log
	// derives from a `Print` function,
	// otherwise true if derives from a `Println`, `Error`, `Errorf`, `Warn`, etc...
	//
	// This NewLine does not mean that `Message` ends with "\n" (or `pio#NewLine`).
	// NewLine has to do with the methods called,
	// not the original content of the `Message`.
	NewLine bool
}

A Log represents a log line.

func (Log) FormatTime

func (l Log) FormatTime() string

FormatTime returns the formatted `Time`.

type Logger

type Logger struct {
	Prefix     []byte
	Level      Level
	TimeFormat string
	// if new line should be added on all log functions, even the `F`s.
	// It defaults to true.
	//
	// See `golog#NewLine(newLineChar string)` as well.
	//
	// Note that this will not override the time and level prefix,
	// if you want to customize the log message please read the examples
	// or navigate to: https://github.com/kataras/golog/issues/3#issuecomment-355895870.
	NewLine bool

	Printer *pio.Printer
	// contains filtered or unexported fields
}

Logger is our golog 简化版.

func New

func New() *Logger

New returns a new golog with a default output to `os.Stdout` and level to `InfoLevel`.

func NewRotateFileLog

func NewRotateFileLog(root, name, lvl, pattern string, rotationTime, maxAge time.Duration) (*Logger, error)

NewRotateFileLog 创建一个根据时间周期切分的文件日志

root: 日志存储的根路径,不能为空
name: 日志的主文件名,可认为为 prefix
lvl: 日志的记录的等级
pattern: 文件名的格式化字符串,如 %Y-%m-%d
rotationTime: 文件切分的间隔
maxAge: 文件最大的时间有效期

func (*Logger) AddOutput

func (l *Logger) AddOutput(writers ...io.Writer) *Logger

AddOutput adds one or more `io.Writer` to the Logger's Printer.

If one of the "writers" is not a terminal-based (i.e File) then colors will be disabled for all outputs.

Returns itself.

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug will print when logger's Level is debug.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf will print when logger's Level is debug.

func (*Logger) DisableNewLine

func (l *Logger) DisableNewLine() *Logger

DisableNewLine disables the new line suffix on every log function, even the `F`'s, the caller should add "\n" to the log message manually after this call.

Returns itself.

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error will print only when logger's Level is error, warn, info or debug.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf will print only when logger's Level is error, warn, info or debug.

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal `os.Exit(1)` exit no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf will `os.Exit(1)` no matter the level of the logger. If the logger's level is fatal, error, warn, info or debug then it will print the log message too.

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info will print when logger's Level is info or debug.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof will print when logger's Level is info or debug.

func (*Logger) Log

func (l *Logger) Log(level Level, v ...interface{})

Log prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.

func (*Logger) Logf

func (l *Logger) Logf(level Level, format string, args ...interface{})

Logf prints a leveled log message to the output. This method can be used to use custom log levels if needed. It adds a new line in the end.

func (*Logger) Print

func (l *Logger) Print(v ...interface{})

Print prints a log message without levels and colors.

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...interface{})

Printf formats according to a format specifier and writes to `Printer#Output` without levels and colors.

func (*Logger) Println

func (l *Logger) Println(v ...interface{})

Println prints a log message without levels and colors. It adds a new line at the end, it overrides the `NewLine` option.

func (*Logger) SetLevel

func (l *Logger) SetLevel(levelName string) *Logger

SetLevel accepts a string representation of a `Level` and returns a `Level` value based on that "levelName".

Available level names are: "disable" "fatal" "error" "warn" "info" "debug"

Alternatively you can use the exported `Level` field, i.e `Level = golog.ErrorLevel`

Returns itself.

func (*Logger) SetOutput

func (l *Logger) SetOutput(w io.Writer) *Logger

SetOutput overrides the Logger's Printer's Output with another `io.Writer`.

Returns itself.

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(s string) *Logger

SetPrefix sets a prefix for this "l" Logger.

The prefix is the first space-separated word that is being presented to the output. It's written even before the log level text.

Returns itself.

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(s string) *Logger

SetTimeFormat sets time format for logs, if "s" is empty then time representation will be off.

Returns itself.

func (*Logger) Warn

func (l *Logger) Warn(v ...interface{})

Warn will print when logger's Level is warn, info or debug.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf will print when logger's Level is warn, info or debug.

type Option

type Option interface {
	Name() string
	Value() interface{}
}

Option is used to pass optional arguments to the RotateLogs constructor

func WithMaxAge

func WithMaxAge(d time.Duration) Option

WithMaxAge creates a new Option that sets the max age of a log file before it gets purged from the file system.

func WithRotationTime

func WithRotationTime(d time.Duration) Option

WithRotationTime creates a new Option that sets the time between rotation.

type RotateWriter

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

RotateWriter represents a log file that gets automatically rotated as you write to it.

func NewRotateWriter

func NewRotateWriter(p string, options ...Option) (*RotateWriter, error)

NewRotateWriter creates a new RotateLogs object. A log filename pattern must be passed. Optional `Option` parameters may be passed

func (*RotateWriter) Write

func (rl *RotateWriter) Write(p []byte) (n int, err error)

Write satisfies the io.Writer interface. It writes to the appropriate file handle that is currently being used. If we have reached rotation time, the target file gets automatically rotated, and also purged if necessary.

Jump to

Keyboard shortcuts

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