log

package
v0.0.0-...-1cd2121 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2019 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LEVELDEBUG = iota
	LEVELINFO
	LEVELWARN
	LEVELERROR
	LEVELFATAL
)

Log level reference java log4j

Variables

View Source
var (
	FgBlack     = "30"
	FgRed       = "31"
	FgGreen     = "32"
	FgYellow    = "33"
	FgBule      = "34"
	FgPurple    = "35"
	FgDarkGreen = "36"
	FgWhite     = "37"
)
View Source
var (
	BgBlack     = "40"
	BgRed       = "41"
	BgGreen     = "42"
	BgYellow    = "43"
	BgBule      = "44"
	BgPurple    = "45"
	BgDarkGreen = "46"
	BgWhite     = "47"
)
View Source
var (
	TCP = regexp.MustCompile(`^tcp\d{0,1}`)
	UDP = regexp.MustCompile(`^udp\d{0,1}`)
)
View Source
var (
	// The log level must be an unsigned integer
	// and must be greater than or equal to DEBUG(uint(1)) and less than or equal to FATAL(uint(5))
	ErrLevel = errors.New("log level setting error")

	// The log writer can't be empty, at least one
	// is needed, and the Writer interface is implemented,
	// otherwise painc will be triggered.
	ErrWriters = errors.New("empty writers")

	// Network type cannot be empty.
	ErrNetType = errors.New("empty network type")

	// Regular expression cannot match specified expression and target value
	ErrMatch = errors.New("unable to match regular expression")
)
View Source
var (
	Flag = os.O_RDWR | os.O_APPEND | os.O_CREATE
	Perm = 0660
)
View Source
var (
	CONN      = "conn"
	CONSOLE   = "console"
	FILE      = "file"
	MULTIFILE = "multifile"
)
View Source
var DefaultTimeFormat = "20060102150405"
View Source
var LoggerMsgPool = &sync.Pool{
	New: func() interface{} {
		return &LoggerMsg{}
	},
}

LoggerMsgPool temporary object, avoiding repeated initialization of LoggerMsg structure pointer

View Source
var PackVersion = [2]byte{'V', '1'}

Functions

func SplitFn

func SplitFn() bufio.SplitFunc

SplitFn function is the function parameter of bufio. According to the incoming byte array and atEOF, it is judged whether the data length and version number, whether the specific data meets the definition of the protocol, and the corresponding complete packet is returned, otherwise it is filtered.

Types

type Adapter

type Adapter interface {
	//  Writing method writes the log bytes to the
	// destination, for example: file, terminal, network,
	// system log component.
	Writing(p []byte) error

	// Flush method flushes the contents of the buffer to the destination.
	Flush()

	// Close method is used to close all open resources.
	Close()
}

type Colour

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

func NewColour

func NewColour() *Colour

NewColour is an initialization constructor that returns a Colour pointer object.

func (*Colour) ColourBackGround

func (c *Colour) ColourBackGround() string

ColourBackGround sets the log background color, unified to black.

func (*Colour) ColourForeGround

func (c *Colour) ColourForeGround(level string) string

ColourForeGround sets the corresponding foreground color according to the log level.

func (*Colour) ColourOutPut

func (c *Colour) ColourOutPut(buf *bytes.Buffer, fg string, msg string)

ColourOutPut method will separate the first and second digits of the original log: level+space, and format the log content from the third digit to the last digit, and finally splicing all the contents and returning.

type Compress

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

func (Compress) DoCompress

func (c Compress) DoCompress(zipName string, path string, sources []string) Task

Closures implement asynchronous compression.

func (Compress) TaskListen

func (c Compress) TaskListen()

Monitor log compression events or context signals.

type ConnObject

type ConnObject struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewConnObject

func NewConnObject(netType string, addrs []string) *ConnObject

NewConnObject is an initialization constructor that returns a ConnObject pointer object.

func (*ConnObject) Close

func (c *ConnObject) Close()

Close net handle resource.

func (*ConnObject) DialFactory

func (c *ConnObject) DialFactory()

DialFactory method will establish an effective network connection based on the network type, server connection address, and timeout period, and store it in c.conns. If the connection fails, the retry will be repeated and the number of retries will be 3.

func (*ConnObject) Flush

func (c *ConnObject) Flush()

func (*ConnObject) SetNetworkType

func (c *ConnObject) SetNetworkType(netType string)

SetNetworkType determines the type of connection based on the incoming netType, trying to make a regular match.

func (*ConnObject) Writing

func (c *ConnObject) Writing(p []byte) error

Writing method is used to transfer the byte array to the server through the established network connection.

type ConsoleObject

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

func NewConsoleObject

func NewConsoleObject() *ConsoleObject

NewConsoleObject is an initialization constructor that returns a ConsoleObject pointer object.

func (*ConsoleObject) Close

func (c *ConsoleObject) Close()

func (*ConsoleObject) Flush

func (c *ConsoleObject) Flush()

func (*ConsoleObject) Writing

func (c *ConsoleObject) Writing(p []byte) error

Writing method is used to write a byte array to os.Stdout or os.Stderr.

type FileObject

type FileObject struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewFileObject

func NewFileObject(path string, rotate, compress, daily bool, opts ...RotateOption) *FileObject

NewConsoleObject is an initialization constructor that returns a FileObject pointer object.

func (*FileObject) Close

func (f *FileObject) Close()

Close file handle resource.

func (*FileObject) Create

func (f *FileObject) Create(path string) error

Create is used to create a log directory.

func (*FileObject) DeleteOld

func (f *FileObject) DeleteOld()

DeleteOld method implements the function of deleting the history log. First, it traverses all the log files in the log directory to obtain two types of log files: 1.zip archive log; 2.program.log.timeunix_num type non-archive log, and then judge whether the log file is satisfied. Delete the condition (has the maximum number of days saved), and delete the history log when it is satisfied. This logic is executed every 24 after the first execution.

func (*FileObject) DoRotate

func (f *FileObject) DoRotate()

DoRotate method implements the specific rotation logic: 1. Close the old log file handle first; 2. Rename the old log, for example: a.log is renamed to a.log.1; 3. Open and generate a new log file handle, The handle pointer is assigned to f; 4. If log compression is configured, the asynchronous compression function will be called, written to chan, and executed asynchronously.

func (*FileObject) Flush

func (f *FileObject) Flush()

Flush will flush the buffer.

func (*FileObject) InitLine

func (f *FileObject) InitLine() int64

InitLine is used to get the total number of rows in the log file. If the file is empty, it returns 0.

func (*FileObject) InitStat

func (f *FileObject) InitStat()

InitStat is used to get the initial information of the file, including: size, number of lines, creation time.

func (*FileObject) Open

func (f *FileObject) Open() (*os.File, error)

Open is used to open a log file and return file handles and errors.

func (*FileObject) RotateByDaily

func (f *FileObject) RotateByDaily() bool

func (*FileObject) RotateByLines

func (f *FileObject) RotateByLines() bool

func (*FileObject) RotateBySizes

func (f *FileObject) RotateBySizes() bool

func (*FileObject) Writing

func (f *FileObject) Writing(p []byte) error

Writing method is used to transfer the byte array to the server through the established network connection.

type Level

type Level uint

type Logger

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

Logger is an active logger that controls all the behavior of the log. Logs can be written to any destination that implements the io.writer method, supporting both synchronous and asynchronous methods.

func NewLogger

func NewLogger(depth int, level ...Level) *Logger

NewLogger is a constructor that returns a pointer to the Logger instance.

func (*Logger) Async

func (l *Logger) Async(ch <-chan *LoggerMsg)

Async provides asynchronous write of logs, implemented by chan.

func (*Logger) CallDepth

func (l *Logger) CallDepth() (file string, line int)

CallDepth gets the file name (short path/full path) and line number of the runtime according to the depth set by the user.

func (*Logger) Close

func (l *Logger) Close()

Close is used to release all resources and exit, including: 1. Asynchronous channel; 2. Each Writes (adapter that implements the interface of Writer).

func (*Logger) ColourAuxiliary

func (l *Logger) ColourAuxiliary(fg string, msg string)

ColourBackGround sets the log background color, unified to black.

func (*Logger) Debug

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

Debug provides input for debug log level and can print the most detailed log information.

func (*Logger) Debugf

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

Debugf provides input for debugf log level and can print the most detailed log information. Support log formatting.

func (*Logger) Error

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

Error provides error level log, such log information must be processed, usually output by internal stack or custom error message.

func (*Logger) Errorf

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

Errorf provides errorf level log, such log information must be processed, usually output by internal stack or custom error message. Support log formatting.

func (*Logger) Fatal

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

Fatal provides fatal level, the most severe (high) log level that must be processed immediately.

func (*Logger) Fatalf

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

Fatalf provides fatalf level, the most severe (high) log level that must be processed immediately. Support log formatting.

func (*Logger) Info

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

Info provides info level logs for displaying basic log information, general user production environment.

func (*Logger) Infof

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

Infof provides infof level logs for displaying basic log information, general user production environment. Support log formatting.

func (*Logger) LevelString

func (l *Logger) LevelString() []string

LevelString method writes a log slice greater than or equal to the currently set to a string slice and returns.

func (*Logger) MBtoBytes

func (l *Logger) MBtoBytes(u int64) int64

MBtoBytes converts MB to B.

func (*Logger) Pack

func (l *Logger) Pack(level, path, msg string, line int, time time.Time) []byte

Pack method is used to assemble messages, including timestamps, log levels, message bodies, log lines (based on log depth), and finally return byte arrays.

func (*Logger) Print

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

Print is to implement the gorm logger interface, so that the framework's log package is compatible with the gorm sql output.

func (*Logger) SetAbsPath

func (l *Logger) SetAbsPath()

SetAbsPath is used to set the absolute file path. If set to true, the absolute path is displayed, for example: a/b/c/d.go; if false, the short path is displayed, for example: d.go. The default is false.

func (*Logger) SetAsynChronous

func (l *Logger) SetAsynChronous(msgLen ...int)

SetAsynChronous sets the log mode to asynchronous.

func (*Logger) SetColour

func (l *Logger) SetColour()

Set whether to display the log in color, the windows system does not display, only valid under the class linux system.

func (*Logger) SetFlag

func (l *Logger) SetFlag()

SetFlag is used to set the level identifier in the log entry. e.g: If set to true, like: [INFO]; set to false, then: [info]. The default is false

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

Set the log level. No need to display the call, only for internal calls.

func (*Logger) SetLinkBeak

func (l *Logger) SetLinkBeak() string

Set the line break of the log line, which needs to be determined according to the operating system. No need to display the call, only for internal calls.

func (*Logger) SetOutput

func (l *Logger) SetOutput(adapter string, cfg map[string]interface{})

SetOutput is used to set the log output to any destination that implements the io.writer method.

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefix string)

SetPrefix sets the log header prefix.

func (*Logger) String

func (l *Logger) String(level uint) string

String method is used to convert the correct uppercase or lowercase log identifier, such as DEBUG or debug. The specific behavior is determined by Logger.flag.

func (*Logger) Warn

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

Warn provides warn level log for displaying warning messages. This information should be of particular concern.

func (*Logger) Warnf

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

Warnf provides warnf level log for displaying warning messages. This information should be of particular concern. Support log formatting.

func (*Logger) Wrapper

func (l *Logger) Wrapper(level string, v ...interface{})

Wrapper implements a global log wrapper According to the log level and log information, the logs are assembled in the specified format. If the log has asynchronous mode enabled, it will be sent to the asynchronous queue, otherwise it will be passed directly to the log writers.

func (*Logger) Wrapperf

func (l *Logger) Wrapperf(level string, format string, v ...interface{})

Wrapperf implements a global formatted log wrapper According to the log level and log information, the logs are assembled in the specified format. If the log has asynchronous mode enabled, it will be sent to the asynchronous queue, otherwise it will be passed directly to the log writers.

func (*Logger) WriteTo

func (l *Logger) WriteTo(level, path, msg string, line int, time time.Time)

WriteTo is the globally unique log output point that iterates over all adapters that implement the Writer interface, calling their Writing method to write all assembled log bytes.

type LoggerMsg

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

LoggerMsg is used to generate the structure of the assembly log message. It mainly includes three elements: time, message, and log level.

type MultiFileObject

type MultiFileObject struct {
	Files []*FileObject
}

func NewMultiFileObject

func NewMultiFileObject(path string, levels []string, rotate, compress, daily bool, lines, size int64, keepDays int) *MultiFileObject

NewMultiFileObject is an initialization constructor that returns a MultiFileObject pointer object.

func (*MultiFileObject) Close

func (m *MultiFileObject) Close()

Close all file handle resources.

func (*MultiFileObject) Flush

func (m *MultiFileObject) Flush()

Flush will flush the cache of all file handles

func (*MultiFileObject) Writing

func (m *MultiFileObject) Writing(p []byte) error

Writing is used to write a byte array to all files. Automatically execute rotate logic and delete logic before writing.

type Protocol

type Protocol struct {
	Version    [2]byte `json:"version"`
	DataLength int16   `json:"data_length"`
	Data       []byte  `json:"data"`
}

func (*Protocol) Pack

func (p *Protocol) Pack(w io.Writer) error

Pack method provides the function of the network byte packet. The sync.pool temporary object pool is used and reused to generate the packet data according to the Protocol protocol structure + big endian for the data read from the io.Writer, then send to the network.

func (*Protocol) String

func (p *Protocol) String() string

Formatted string output.

func (*Protocol) Unpack

func (p *Protocol) Unpack(r io.Reader) error

Unpack method provides the function of unpacking network bytes. After reading data from the io.Reader interface in big endian, unpacking.

type Rotate

type Rotate struct {
	// Rotary counter
	Count int

	// Rotate by max lines
	MaxLines    int64
	CurrentLine int64

	// Rotate by max size
	MaxSize     int64
	CurrentSize int64

	// Rotate by max days
	MaxKeepDays int
	CurrentTime time.Time
}

type RotateOption

type RotateOption func(*Rotate)

func WithMaxDaysOption

func WithMaxDaysOption(d int) RotateOption

WithMaxDaysOption is an optional function, the maximum number of days to save log files can be configured through the function option mode.

func WithMaxLinesOption

func WithMaxLinesOption(l int64) RotateOption

WithMaxLinesOption is an optional function, the maximum number of rows of log files can be configured through the function option mode.

func WithMaxSizeOption

func WithMaxSizeOption(s int64) RotateOption

WithMaxSizeOption is an optional function, the maximum size of the log file can be configured through the function option mode.

type Task

type Task func() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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