Documentation ¶
Overview ¶
Package log implements logging with severity levels and message categories.
Index ¶
- Constants
- Variables
- func Categories() []string
- func Close()
- func DateFormatFilename(dfile string) (prefix string, suffix, dateformat string, filename string, err error)
- func Debug(a ...interface{})
- func Debugf(format string, a ...interface{})
- func DefaultFormatter(l *Logger, e *Entry) string
- func Dump(v interface{}, returnOnly ...bool) string
- func EmojiOfLevel(level Level) string
- func EmptyFormatter(l *Logger, e *Entry) string
- func Error(a ...interface{})
- func Errorf(format string, a ...interface{})
- func Fatal(a ...interface{})
- func Fatalf(format string, a ...interface{})
- func ForceCreateSymlink(source, dest string) error
- func GetCallSingleStack(skip int, filters ...string) (fileName string, lineNo int, found bool)
- func GetCallStack(skip int, frames int, filters ...string) string
- func GetLevelEmoji(l Level) string
- func HTTPStatusLevelName(httpCode int) string
- func HasCategory(category string) bool
- func Info(a ...interface{})
- func Infof(format string, a ...interface{})
- func IsEnabled(level Level) bool
- func JSONFormatter(l *Logger, e *Entry) string
- func NewHttpLevel(code int, level Leveler) *httpLevel
- func NormalFormatter(l *Logger, e *Entry) string
- func Okay(a ...interface{})
- func Okayf(format string, a ...interface{})
- func Progress(a ...interface{})
- func Progressf(format string, a ...interface{})
- func Warn(a ...interface{})
- func Warnf(format string, a ...interface{})
- func Writer(level Level) io.Writer
- type Action
- type CallStack
- type ConsoleTarget
- type Entry
- type FileTarget
- type Filter
- type Formatter
- type JSONL
- type Level
- type Leveler
- type Logger
- func AddTarget(targets ...Target) *Logger
- func Async(args ...bool) *Logger
- func GetLogger(category string, formatter ...Formatter) *Logger
- func New(args ...string) *Logger
- func NewLogger(args ...string) *Logger
- func SetCallStack(level Level, callStack *CallStack) *Logger
- func SetEmoji(on bool) *Logger
- func SetFatalAction(action Action) *Logger
- func SetFormatter(formatter Formatter) *Logger
- func SetLevel(level string) *Logger
- func SetTarget(targets ...Target) *Logger
- func Sync(args ...bool) *Logger
- func UseCommonTargets(levelName string, targetNames ...string) *Logger
- func (l *Logger) AddTarget(targets ...Target) *Logger
- func (l *Logger) Async(args ...bool) *Logger
- func (l *Logger) Categories() []string
- func (l Logger) Close()
- func (l *Logger) Debug(a ...interface{})
- func (l *Logger) Debugf(format string, a ...interface{})
- func (l *Logger) EmojiOfLevel(level Level) string
- func (l *Logger) Error(a ...interface{})
- func (l *Logger) Errorf(format string, a ...interface{})
- func (l *Logger) Fatal(a ...interface{})
- func (l *Logger) Fatalf(format string, a ...interface{})
- func (l *Logger) GetLogger(category string, formatter ...Formatter) *Logger
- func (l *Logger) HasCategory(category string) bool
- func (l *Logger) Info(a ...interface{})
- func (l *Logger) Infof(format string, a ...interface{})
- func (l *Logger) IsEnabled(level Level) bool
- func (l *Logger) Log(level Leveler, a ...interface{})
- func (l *Logger) Logf(level Leveler, format string, a ...interface{})
- func (l *Logger) Okay(a ...interface{})
- func (l *Logger) Okayf(format string, a ...interface{})
- func (l Logger) Open() error
- func (l Logger) Pid() int
- func (l *Logger) Progress(a ...interface{})
- func (l *Logger) Progressf(format string, a ...interface{})
- func (l *Logger) SetCallStack(level Level, callStack *CallStack) *Logger
- func (l *Logger) SetEmoji(on bool) *Logger
- func (l *Logger) SetFatalAction(action Action) *Logger
- func (l *Logger) SetFormatter(formatter Formatter) *Logger
- func (l *Logger) SetLevel(level string) *Logger
- func (l *Logger) SetTarget(targets ...Target) *Logger
- func (l *Logger) Sync(args ...bool) *Logger
- func (l *Logger) Warn(a ...interface{})
- func (l *Logger) Warnf(format string, a ...interface{})
- func (l *Logger) Writer(level Level) io.Writer
- type LoggerWriter
- type MailTarget
- type NetworkTarget
- type SyslogTarget
- type Target
- type WriteCloserTarget
Examples ¶
Constants ¶
const ( // STATE INDICATORS Red = "🔴" Ylw = "🟡" Blu = "🔵" Grn = "🟢" Org = "🟠" Pnk = "🟣" EmojiFatal = "💀" EmojiError = "❌" EmojiWarn = "🟡" EmojiOkay = "✅" EmojiInfo = "💬" EmojiProgress = "⌛️" EmojiDebug = "🐛" )
Success, Warning, Error can also be summary items. Grn, Ylw, Red are calm B/G indicator lights .
const ( ColorFlag = iota ColorRow )
Variables ¶
var ( DefaultStackDepth = 5 DefaultSkipStack = 3 DefaultStackFilter = `github.com/admpub/log` )
var ( // target console DefaultConsoleColorize = !color.NoColor // target file DefaultFileMaxBytes int64 = 100 * 1024 * 1024 // 100M DefaultFileBackupCount = 30 // 30 // target network DefaultNetworkType = `tcp` DefaultNetworkAddress = `` // target mail DefaultMailHost = `` DefaultMailUsername = `` DefaultMailPassword = `` DefaultMailSubject = `` DefaultMailSender = `` DefaultMailRecipients = []string{} )
var ( // LevelNames maps log levels to names LevelNames = map[Leveler]string{ LevelDebug: "Debug", LevelProgress: "Progress", LevelInfo: "Info", LevelOkay: "Okay", LevelWarn: "Warn", LevelError: "Error", LevelFatal: "Fatal", } // LevelUppers 日志大写名称前缀 LevelUppers = map[string]string{ `Debug`: "DEBUG", "Progress": "PROGR", `Info`: " INFO", "Okay": " OKAY", `Warn`: " WARN", `Error`: "ERROR", `Fatal`: "FATAL", } // Levels 所有日志等级 Levels = map[string]Leveler{ "Debug": LevelDebug, "Progress": LevelProgress, "Info": LevelInfo, "Okay": LevelOkay, "Warn": LevelWarn, "Error": LevelError, "Fatal": LevelFatal, } )
var DefaultLog = &defaultLogger{Logger: New()}
DefaultLog 默认日志实例
var Emojis = map[Level]string{ LevelFatal: EmojiFatal, LevelError: EmojiError, LevelWarn: EmojiWarn, LevelOkay: EmojiOkay, LevelInfo: EmojiInfo, LevelProgress: EmojiProgress, LevelDebug: EmojiDebug, }
Functions ¶
func Categories ¶ added in v1.2.2
func Categories() []string
func DateFormatFilename ¶
func DefaultFormatter ¶
DefaultFormatter is the default formatter used to format every log message.
func EmojiOfLevel ¶ added in v1.1.0
func EmptyFormatter ¶ added in v1.1.5
func ForceCreateSymlink ¶ added in v1.3.4
func GetCallSingleStack ¶
GetCallSingleStack 获取单个记录
func GetCallStack ¶
GetCallStack returns the current call stack information as a string. The skip parameter specifies how many top frames should be skipped, while the frames parameter specifies at most how many frames should be returned.
func GetLevelEmoji ¶ added in v1.1.6
func HTTPStatusLevelName ¶
HTTPStatusLevelName HTTP状态码相应级别名称
func HasCategory ¶ added in v1.2.2
func NewHttpLevel ¶
Types ¶
type ConsoleTarget ¶
type ConsoleTarget struct { *Filter ColorMode bool // whether to use colors to differentiate log levels ColorType int Writer io.Writer // the writer to write log messages // contains filtered or unexported fields }
ConsoleTarget writes filtered log messages to console window.
func NewConsoleTarget ¶
func NewConsoleTarget() *ConsoleTarget
NewConsoleTarget creates a ConsoleTarget. The new ConsoleTarget takes these default options: MaxLevel: LevelDebug, ColorMode: true, Writer: os.Stdout
Example ¶
package main import ( "github.com/admpub/log" ) func main() { logger := log.NewLogger() // creates a ConsoleTarget with color mode being disabled target := log.NewConsoleTarget() target.ColorMode = false logger.Targets = append(logger.Targets, target) logger.Open() // ... logger is ready to use ... }
Output:
func (*ConsoleTarget) ColorizeFlag ¶
func (t *ConsoleTarget) ColorizeFlag(e *Entry) string
func (*ConsoleTarget) ColorizeRow ¶
func (t *ConsoleTarget) ColorizeRow(e *Entry) string
func (*ConsoleTarget) Open ¶
func (t *ConsoleTarget) Open(io.Writer) error
Open prepares ConsoleTarget for processing log messages.
func (*ConsoleTarget) Process ¶
func (t *ConsoleTarget) Process(e *Entry)
Process writes a log message using Writer.
type Entry ¶
type Entry struct { Level Leveler Category string Message string Time time.Time CallStack string FormattedMessage string }
Entry represents a log entry.
type FileTarget ¶
type FileTarget struct { *Filter // the log file name. When Rotate is true, log file name will be suffixed // to differentiate different backup copies (e.g. app.log.1) FileName string // whether to enable file rotating at specific time interval or when maximum file size is reached. Rotate bool // how many log files should be kept when Rotate is true (the current log file is not included). // This field is ignored when Rotate is false. BackupCount int // maximum number of bytes allowed for a log file. Zero means no limit. // This field is ignored when Rotate is false. MaxBytes int64 SymlinkName string DisableSymlink bool // contains filtered or unexported fields }
FileTarget writes filtered log messages to a file. FileTarget supports file rotation by keeping certain number of backup log files.
func NewFileTarget ¶
func NewFileTarget() *FileTarget
NewFileTarget creates a FileTarget. The new FileTarget takes these default options: MaxLevel: LevelDebug, Rotate: true, BackupCount: 10, MaxBytes: 1 << 20 You must specify the FileName field.
Example ¶
package main import ( "github.com/admpub/log" ) func main() { logger := log.NewLogger() // creates a FileTarget which keeps log messages in the app.log file target := log.NewFileTarget() target.FileName = "app.log" logger.Targets = append(logger.Targets, target) logger.Open() // ... logger is ready to use ... }
Output:
func (*FileTarget) ClearFiles ¶ added in v1.1.2
func (t *FileTarget) ClearFiles()
func (*FileTarget) CountFiles ¶ added in v1.1.2
func (t *FileTarget) CountFiles() int
func (*FileTarget) Fd ¶ added in v1.3.5
func (t *FileTarget) Fd() (fd *os.File)
func (*FileTarget) Open ¶
func (t *FileTarget) Open(errWriter io.Writer) (err error)
Open prepares FileTarget for processing log messages.
func (*FileTarget) Process ¶
func (t *FileTarget) Process(e *Entry)
Process saves an allowed log message into the log file.
type Filter ¶
type Filter struct { MaxLevel Leveler // the maximum severity level that is allowed Levels map[Leveler]bool // 此属性被设置时,MaxLevel 无效 Categories []string // the allowed message categories. Categories can use "*" as a suffix for wildcard matching. // contains filtered or unexported fields }
Filter checks if a log message meets the level and category requirements.
func (*Filter) Allow ¶
Allow checks if a message meets the severity level and category requirements.
type Formatter ¶
Formatter formats a log message into an appropriate string.
func ShortFileFormatter ¶
ShortFileFormatter 简介文件名格式
type JSONL ¶
type JSONL struct { Time string `bson:"time" json:"time"` Level string `bson:"level" json:"level"` Category string `bson:"category" json:"category"` Message json.RawMessage `bson:"message" json:"message"` CallStack string `bson:"callStack" json:"callStack"` Pid int `bson:"pid" json:"pid"` }
JSONL json格式信息
type Level ¶
type Level int
Level 日志等级编号
RFC5424 log message levels.
type Leveler ¶
type Leveler interface { fmt.Stringer IsEnabled(level Level) bool Int() int Tag() string Color() *color.Color Level() Level }
Leveler 日志等级接口
type Logger ¶
type Logger struct { Category string // the category associated with this logger Formatter Formatter // message formatter Emoji bool // contains filtered or unexported fields }
Logger records log messages and dispatches them to various targets for further processing.
func NewLogger ¶
NewLogger creates a root logger. The new logger takes these default options: ErrorWriter: os.Stderr, BufferSize: 1024, MaxLevel: LevelDebug, Category: app, Formatter: DefaultFormatter
func SetCallStack ¶ added in v0.2.1
func SetFatalAction ¶
func SetFormatter ¶
func UseCommonTargets ¶
func (*Logger) Categories ¶ added in v1.2.2
func (Logger) Close ¶
func (l Logger) Close()
Close closes the logger and the targets. Existing messages will be processed before the targets are closed. New incoming messages will be discarded after calling this method.
func (*Logger) Debug ¶
func (l *Logger) Debug(a ...interface{})
Debug logs a message for debugging purpose. Please refer to Error() for how to use this method.
func (*Logger) Debugf ¶
Debugf logs a message for debugging purpose. Please refer to Error() for how to use this method.
func (*Logger) EmojiOfLevel ¶ added in v1.1.6
func (*Logger) Error ¶
func (l *Logger) Error(a ...interface{})
Error logs a message indicating an error condition. This method takes one or multiple parameters. If a single parameter is provided, it will be treated as the log message. If multiple parameters are provided, they will be passed to fmt.Sprintf() to generate the log message.
Example ¶
package main import ( "github.com/admpub/log" ) func main() { logger := log.NewLogger() logger.Targets = append(logger.Targets, log.NewConsoleTarget()) logger.Open() // log without formatting logger.Error("a plain message") // log with formatting logger.Errorf("the value is: %v", 100) }
Output:
func (*Logger) Errorf ¶
Errorf logs a message indicating an error condition. This method takes one or multiple parameters. If a single parameter is provided, it will be treated as the log message. If multiple parameters are provided, they will be passed to fmt.Sprintf() to generate the log message.
func (*Logger) GetLogger ¶
GetLogger creates a logger with the specified category and log formatter. Messages logged through this logger will carry the same category name. The formatter, if not specified, will inherit from the calling logger. It will be used to format all messages logged through this logger.
func (*Logger) HasCategory ¶ added in v1.2.2
func (*Logger) Info ¶
func (l *Logger) Info(a ...interface{})
Info logs a message for informational purpose. Please refer to Error() for how to use this method.
func (*Logger) Infof ¶
Infof logs a message for informational purpose. Please refer to Error() for how to use this method.
func (*Logger) Okay ¶ added in v1.1.0
func (l *Logger) Okay(a ...interface{})
Okay logs a message indicating an okay condition.
func (Logger) Open ¶
func (l Logger) Open() error
Open prepares the logger and the targets for logging purpose. Open must be called before any message can be logged.
func (*Logger) Progress ¶ added in v1.1.0
func (l *Logger) Progress(a ...interface{})
Progress logs a message for how things are progressing.
func (*Logger) SetCallStack ¶ added in v0.2.1
SetCallStack 设置各个等级的call stack配置
func (*Logger) SetFatalAction ¶
SetFatalAction 设置Fatal类型日志的行为
func (*Logger) SetFormatter ¶
SetFormatter 设置日志格式化处理函数
func (*Logger) Warn ¶
func (l *Logger) Warn(a ...interface{})
Warn logs a message indicating a warning condition. Please refer to Error() for how to use this method.
type LoggerWriter ¶
func (LoggerWriter) Close ¶
func (l LoggerWriter) Close()
Close closes the logger and the targets. Existing messages will be processed before the targets are closed. New incoming messages will be discarded after calling this method.
func (LoggerWriter) Open ¶
func (l LoggerWriter) Open() error
Open prepares the logger and the targets for logging purpose. Open must be called before any message can be logged.
func (*LoggerWriter) Printf ¶
func (l *LoggerWriter) Printf(format string, v ...interface{})
func (*LoggerWriter) Println ¶
func (l *LoggerWriter) Println(v ...interface{})
type MailTarget ¶
type MailTarget struct { *Filter Host string // SMTP server address Username string // SMTP server login username Password string // SMTP server login password Subject string // the mail subject Sender string // the mail sender Recipients []string // the mail recipients BufferSize int // the size of the message channel. // contains filtered or unexported fields }
MailTarget sends log messages in emails via an SMTP server.
func NewMailTarget ¶
func NewMailTarget() *MailTarget
NewMailTarget creates a MailTarget. The new MailTarget takes these default options: MaxLevel: LevelDebug, BufferSize: 1024. You must specify these fields: Host, Username, Subject, Sender, and Recipients.
Example ¶
package main import ( "github.com/admpub/log" ) func main() { logger := log.NewLogger() // creates a MailTarget which sends emails to admin@example.com target := log.NewMailTarget() target.Host = "smtp.example.com" target.Username = "foo" target.Password = "bar" target.Subject = "log messages for foobar" target.Sender = "admin@example.com" target.Recipients = []string{"admin@example.com"} logger.Targets = append(logger.Targets, target) logger.Open() // ... logger is ready to use ... }
Output:
func (*MailTarget) Open ¶
func (t *MailTarget) Open(errWriter io.Writer) error
Open prepares MailTarget for processing log messages.
func (*MailTarget) Process ¶
func (t *MailTarget) Process(e *Entry)
Process puts filtered log messages into a channel for sending in emails.
type NetworkTarget ¶
type NetworkTarget struct { *Filter // the network to connect to. Valid networks include // tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), // "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" // (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and // "unixpacket". Network string // the address on the network to connect to. // For TCP and UDP networks, addresses have the form host:port. // If host is a literal IPv6 address it must be enclosed // in square brackets as in "[::1]:80" or "[ipv6-host%zone]:80". Address string // whether to use a persistent network connection. // If this is false, for every message to be sent, a network // connection will be open and closed. Persistent bool // the size of the message channel. BufferSize int // contains filtered or unexported fields }
NetworkTarget sends log messages over a network connection.
func NewNetworkTarget ¶
func NewNetworkTarget() *NetworkTarget
NewNetworkTarget creates a NetworkTarget. The new NetworkTarget takes these default options: MaxLevel: LevelDebug, Persistent: true, BufferSize: 1024. You must specify the Network and Address fields.
Example ¶
package main import ( "github.com/admpub/log" ) func main() { logger := log.NewLogger() // creates a NetworkTarget which uses tcp network and address :10234 target := log.NewNetworkTarget() target.Network = "tcp" target.Address = ":10234" logger.Targets = append(logger.Targets, target) logger.Open() // ... logger is ready to use ... }
Output:
func (*NetworkTarget) Open ¶
func (t *NetworkTarget) Open(errWriter io.Writer) error
Open prepares NetworkTarget for processing log messages.
func (*NetworkTarget) Process ¶
func (t *NetworkTarget) Process(e *Entry)
Process puts filtered log messages into a channel for sending over network.
type SyslogTarget ¶ added in v1.1.0
type SyslogTarget struct { *Filter Writer *syslog.Writer // contains filtered or unexported fields }
func NewSyslogTarget ¶ added in v1.1.0
func NewSyslogTarget(prefix string) (*SyslogTarget, error)
func (*SyslogTarget) Close ¶ added in v1.1.0
func (t *SyslogTarget) Close()
func (*SyslogTarget) Process ¶ added in v1.1.0
func (t *SyslogTarget) Process(e *Entry)
type Target ¶
type Target interface { // Open prepares the target for processing log messages. // Open will be invoked when Logger.Open() is called. // If an error is returned, the target will be removed from the logger. // errWriter should be used to write errors found while processing log messages. Open(errWriter io.Writer) error // Process processes an incoming log message. Process(*Entry) // Close closes a target. // Close is called when Logger.Close() is called, which gives each target // a chance to flush the logged messages to their destination storage. Close() SetLevel(interface{}) SetLevels(...Leveler) }
Target represents a target where the logger can send log messages to for further processing.
type WriteCloserTarget ¶
type WriteCloserTarget struct { io.WriteCloser *Filter // contains filtered or unexported fields }
WriteCloserTarget writes filtered log messages to a io.WriteCloser.
func NewWriteCloserTarget ¶
func NewWriteCloserTarget(w io.WriteCloser) *WriteCloserTarget
NewWriteCloserTarget creates a WriteCloserTarget.
func (*WriteCloserTarget) Open ¶
func (t *WriteCloserTarget) Open(errWriter io.Writer) (err error)
Open nothing.
func (*WriteCloserTarget) Process ¶
func (t *WriteCloserTarget) Process(e *Entry)
Process writes a log message using Writer.