logs

package
v0.0.0-...-956f19d Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 24 Imported by: 2

Documentation

Overview

Package logs provide a general log interface Usage:

import "github.com/mdaxf/iac/framework/logs"

log := NewLogger(10000)
log.SetLogger("console", "")

> the first params stand for how many channel

Use it like this:

log.Trace("trace")
log.Info("info")
log.Warn("warning")
log.Debug("debug")
log.Critical("critical")

Index

Constants

View Source
const (
	LevelEmergency = iota
	LevelAlert
	LevelCritical
	LevelError
	LevelWarning
	LevelNotice
	LevelInformational
	LevelDebug
	LeverPerformance
)

RFC5424 log message levels.

View Source
const (
	AdapterConsole    = "console"
	AdapterFile       = "file"
	AdapterMultiFile  = "multifile"
	AdapterMail       = "smtp"
	AdapterConn       = "conn"
	AdapterEs         = "es"
	AdapterSlack      = "slack"
	AdapterAliLS      = "alils"
	AdapterDocumentDB = "documentdb"
)

Name for adapter with iac official support

View Source
const (
	LevelInfo  = LevelInformational
	LevelTrace = LevelDebug
	LevelWarn  = LevelWarning
)

Legacy log level constants to ensure backwards compatibility.

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(r *AccessLogRecord, format string)

AccessLog - Format and print access log.

func Alert

func Alert(f interface{}, v ...interface{})

Alert logs a message at alert level.

func ColorByMethod

func ColorByMethod(method string) string

ColorByMethod return color by http code

func ColorByStatus

func ColorByStatus(code int) string

ColorByStatus return color by http code 2xx return Green 3xx return White 4xx return Yellow 5xx return Red

func Critical

func Critical(f interface{}, v ...interface{})

Critical logs a message at critical level.

func Debug

func Debug(f interface{}, v ...interface{})

Debug logs a message at debug level.

func Emergency

func Emergency(f interface{}, v ...interface{})

Emergency logs a message at emergency level.

func EnableFullFilePath

func EnableFullFilePath(b bool)

EnableFullFilePath enables full file path logging. Disabled by default e.g "/home/Documents/GitHub/iac/mainapp/" instead of "mainapp"

func EnableFuncCallDepth

func EnableFuncCallDepth(b bool)

EnableFuncCallDepth enable log funcCallDepth

func Error

func Error(f interface{}, v ...interface{})

Error logs a message at error level.

func GetLogger

func GetLogger(prefixes ...string) *log.Logger

GetLogger returns the default IACLogger

func Info

func Info(f interface{}, v ...interface{})

Info compatibility alias for Warning()

func Informational

func Informational(f interface{}, v ...interface{})

Informational logs a message at info level.

func Notice

func Notice(f interface{}, v ...interface{})

Notice logs a message at notice level.

func Register

func Register(name string, log newLoggerFunc)

Register makes a log provide available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

func RegisterFormatter

func RegisterFormatter(name string, fmtr LogFormatter)

RegisterFormatter register an formatter. Usually you should use this to extend your custom formatter for example: RegisterFormatter("my-fmt", &MyFormatter{}) logs.SetFormatter(Console, `{"formatter": "my-fmt"}`)

func Reset

func Reset()

Reset will remove all the adapter

func ResetColor

func ResetColor() string

ResetColor return reset color

func SetGlobalFormatter

func SetGlobalFormatter(fmtter string) error

SetGlobalFormatter sets the global formatter for all log adapters don't forget to register the formatter by invoking RegisterFormatter

func SetLevel

func SetLevel(l int)

SetLevel sets the global log level used by the simple logger.

func SetLogFuncCall

func SetLogFuncCall(b bool)

SetLogFuncCall set the CallDepth, default is 4

func SetLogFuncCallDepth

func SetLogFuncCallDepth(d int)

SetLogFuncCallDepth set log funcCallDepth

func SetLogger

func SetLogger(adapter string, config ...string) error

SetLogger sets a new logger.

func SetPrefix

func SetPrefix(s string)

SetPrefix sets the prefix

func Trace

func Trace(f interface{}, v ...interface{})

Trace logs a message at trace level. compatibility alias for Warning()

func Warn

func Warn(f interface{}, v ...interface{})

Warn compatibility alias for Warning()

func Warning

func Warning(f interface{}, v ...interface{})

Warning logs a message at warning level.

Types

type AccessLogRecord

type AccessLogRecord struct {
	RemoteAddr     string        `json:"remote_addr"`
	RequestTime    time.Time     `json:"request_time"`
	RequestMethod  string        `json:"request_method"`
	Request        string        `json:"request"`
	ServerProtocol string        `json:"server_protocol"`
	Host           string        `json:"host"`
	Status         int           `json:"status"`
	BodyBytesSent  int64         `json:"body_bytes_sent"`
	ElapsedTime    time.Duration `json:"elapsed_time"`
	HTTPReferrer   string        `json:"http_referrer"`
	HTTPUserAgent  string        `json:"http_user_agent"`
	RemoteUser     string        `json:"remote_user"`
}

AccessLogRecord is astruct for holding access log data.

type IACLogger

type IACLogger struct {
	Perf     bool
	Threhold int
	// contains filtered or unexported fields
}

IACLogger is default logger in iac application. Can contain several providers and log message into all providers.

func Async

func Async(msgLen ...int64) *IACLogger

Async set the beelogger with Async mode and hold msglen messages

func GetIACLogger

func GetIACLogger() *IACLogger

GetIACLogger returns the default IACLogger

func New

func New() *IACLogger

func NewLogger

func NewLogger(channelLens ...int64) *IACLogger

NewLogger returns a new IACLogger. channelLen: the number of messages in chan(used where asynchronous is true). if the buffering chan is full, logger adapters write to file or other way. func NewLogger(channelLens ...int64) *IACLogger {

func (*IACLogger) Alert

func (bl *IACLogger) Alert(format string, v ...interface{})

Alert Log ALERT level message.

func (*IACLogger) Async

func (bl *IACLogger) Async(msgLen ...int64) *IACLogger

Async sets the log to asynchronous and start the goroutine

func (*IACLogger) AsyncNonBlockWrite

func (bl *IACLogger) AsyncNonBlockWrite() *IACLogger

AsyncNonBlockWrite Non-blocking write in asynchronous mode Only works if asynchronous write logging is set

func (*IACLogger) Close

func (bl *IACLogger) Close()

Close close logger, flush all chan data and destroy all adapters in IACLogger.

func (*IACLogger) Critical

func (bl *IACLogger) Critical(format string, v ...interface{})

Critical Log CRITICAL level message.

func (*IACLogger) Debug

func (bl *IACLogger) Debug(format string, v ...interface{})

Debug Log DEBUG level message.

func (*IACLogger) DelLogger

func (bl *IACLogger) DelLogger(adapterName string) error

DelLogger removes a logger adapter in IACLogger.

func (*IACLogger) Emergency

func (bl *IACLogger) Emergency(format string, v ...interface{})

Emergency Log EMERGENCY level message.

func (*IACLogger) EnableFuncCallDepth

func (bl *IACLogger) EnableFuncCallDepth(b bool)

EnableFuncCallDepth enable log funcCallDepth

func (*IACLogger) Error

func (bl *IACLogger) Error(format string, v ...interface{})

Error Log ERROR level message.

func (*IACLogger) Flush

func (bl *IACLogger) Flush()

Flush flush all chan data.

func (*IACLogger) GetLevel

func (bl *IACLogger) GetLevel() int

GetLevel Get Current log message level.

func (*IACLogger) GetLogFuncCallDepth

func (bl *IACLogger) GetLogFuncCallDepth() int

GetLogFuncCallDepth return log funcCallDepth for wrapper

func (*IACLogger) Info

func (bl *IACLogger) Info(format string, v ...interface{})

Info Log INFO level message. compatibility alias for Informational()

func (*IACLogger) Informational

func (bl *IACLogger) Informational(format string, v ...interface{})

Informational Log INFORMATIONAL level message.

func (*IACLogger) Notice

func (bl *IACLogger) Notice(format string, v ...interface{})

Notice Log NOTICE level message.

func (*IACLogger) Performance

func (bl *IACLogger) Performance(elapsed time.Duration, format string, v ...interface{})

Performance level message./

func (*IACLogger) Reset

func (bl *IACLogger) Reset()

Reset close all outputs, and set bl.outputs to nil

func (*IACLogger) SetLevel

func (bl *IACLogger) SetLevel(l int)

SetLevel sets log message level. If message level (such as LevelDebug) is higher than logger level (such as LevelWarning), log providers will not be sent the message.

func (*IACLogger) SetLogFuncCallDepth

func (bl *IACLogger) SetLogFuncCallDepth(d int)

SetLogFuncCallDepth set log funcCallDepth

func (*IACLogger) SetLogger

func (bl *IACLogger) SetLogger(adapterName string, configs ...string) error

SetLogger provides a given logger adapter into IACLogger with config string. config must in in JSON format like {"interval":360}}

func (*IACLogger) SetPrefix

func (bl *IACLogger) SetPrefix(s string)

set prefix

func (*IACLogger) Trace

func (bl *IACLogger) Trace(format string, v ...interface{})

Trace Log TRACE level message. compatibility alias for Debug()

func (*IACLogger) Warn

func (bl *IACLogger) Warn(format string, v ...interface{})

Warn Log WARN level message. compatibility alias for Warning()

func (*IACLogger) Warning

func (bl *IACLogger) Warning(format string, v ...interface{})

Warning Log WARNING level message.

func (*IACLogger) Write

func (bl *IACLogger) Write(p []byte) (n int, err error)

type LogFormatter

type LogFormatter interface {
	Format(lm *LogMsg) string
}

func GetFormatter

func GetFormatter(name string) (LogFormatter, bool)

type LogMsg

type LogMsg struct {
	Level      int
	Msg        string
	When       time.Time
	FilePath   string
	LineNumber int
	Args       []interface{}
	Prefix     string
	// contains filtered or unexported fields
}

func (*LogMsg) OldStyleFormat

func (lm *LogMsg) OldStyleFormat() string

OldStyleFormat you should never invoke this

type Logger

type Logger interface {
	Init(config string) error
	WriteMsg(lm *LogMsg) error
	Destroy()
	Flush()
	SetFormatter(f LogFormatter)
}

Logger defines the behavior of a log provider.

func NewConsole

func NewConsole() Logger

NewConsole creates ConsoleWriter returning as LoggerInterface.

type PatternLogFormatter

type PatternLogFormatter struct {
	Pattern    string
	WhenFormat string
}

PatternLogFormatter provides a quick format method for example: tes := &PatternLogFormatter{Pattern: "%F:%n|%w %t>> %m", WhenFormat: "2006-01-02"} RegisterFormatter("tes", tes) SetGlobalFormatter("tes")

func (*PatternLogFormatter) Format

func (p *PatternLogFormatter) Format(lm *LogMsg) string

func (*PatternLogFormatter) ToString

func (p *PatternLogFormatter) ToString(lm *LogMsg) string

ToString 'w' when, 'm' msg,'f' filename,'F' full path,'n' line number 'l' level number, 't' prefix of level type, 'T' full name of level type

type SMTPWriter

type SMTPWriter struct {
	Username           string   `json:"username"`
	Password           string   `json:"password"`
	Host               string   `json:"host"`
	Subject            string   `json:"subject"`
	FromAddress        string   `json:"fromAddress"`
	RecipientAddresses []string `json:"sendTos"`
	Level              int      `json:"level"`

	Formatter string `json:"formatter"`
	// contains filtered or unexported fields
}

SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server.

func (*SMTPWriter) Destroy

func (s *SMTPWriter) Destroy()

Destroy implementing method. empty.

func (*SMTPWriter) Flush

func (s *SMTPWriter) Flush()

Flush implementing method. empty.

func (*SMTPWriter) Format

func (s *SMTPWriter) Format(lm *LogMsg) string

func (*SMTPWriter) Init

func (s *SMTPWriter) Init(config string) error

Init smtp writer with json config. config like:

{
	"username":"example@gmail.com",
	"password:"password",
	"host":"smtp.gmail.com:465",
	"subject":"email title",
	"fromAddress":"from@example.com",
	"sendTos":["email1","email2"],
	"level":LevelError
}

func (*SMTPWriter) SetFormatter

func (s *SMTPWriter) SetFormatter(f LogFormatter)

func (*SMTPWriter) WriteMsg

func (s *SMTPWriter) WriteMsg(lm *LogMsg) error

WriteMsg writes message in smtp writer. Sends an email with subject and only this message.

Jump to

Keyboard shortcuts

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