log

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2020 License: MIT Imports: 7 Imported by: 32

README

log

Go GitHub tag (latest SemVer) Sourcegraph GoDoc go.dev Go Report Card FOSSA Status Coverage Status

Common Interfaces for logging

Here:

type (
	// Logger is a minimal logger with no more dependencies
	Logger interface {
		// Tracef prints the text to stdin if logging level is greater than TraceLevel
		Tracef(msg string, args ...interface{})
		// Debugf prints the text to stdin if logging level is greater than DebugLevel
		Debugf(msg string, args ...interface{})
		// Infof prints the text to stdin if logging level is greater than InfoLevel
		Infof(msg string, args ...interface{})
		// Warnf prints the text to stderr
		Warnf(msg string, args ...interface{})
		// Errorf prints the text to stderr
		Errorf(msg string, args ...interface{})
		// Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
		Fatalf(msg string, args ...interface{})
		// Panicf is equivalent to Printf() followed by a call to panic().
		Panicf(msg string, args ...interface{})
		// Printf calls Output to print to the standard logger.
		// Arguments are handled in the manner of fmt.Printf.
		Printf(msg string, args ...interface{})

		// SetLevel sets the logging level
		SetLevel(lvl Level)
		// GetLevel returns the current logging level
		GetLevel() Level

		// Setup will be invoked once an instance created
		Setup()

		// AsFieldLogger() FieldLogger
	}

	// LoggerConfig is used for creating a minimal logger with no more dependencies
	LoggerConfig struct {
		Enabled   bool
		Backend   string // zap, sugar, logrus
		Level     string
		Format    string // text, json, ...
		Target    string // console, file, console+file
		Directory string
		DebugMode bool `json:"-" yaml:"-"`
		TraceMode bool `json:"-" yaml:"-"`

		// the following options are copied from zap rotator

		// MaxSize is the maximum size in megabytes of the log file before it gets
		// rotated. It defaults to 100 megabytes.
		MaxSize int `json:"maxsize" yaml:"maxsize"`

		// MaxAge is the maximum number of days to retain old log files based on the
		// timestamp encoded in their filename.  Note that a day is defined as 24
		// hours and may not exactly correspond to calendar days due to daylight
		// savings, leap seconds, etc. The default is not to remove old log files
		// based on age.
		MaxAge int `json:"maxage" yaml:"maxage"`

		// MaxBackups is the maximum number of old log files to retain.  The default
		// is to retain all old log files (though MaxAge may still cause them to get
		// deleted.)
		MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

		// LocalTime determines if the time used for formatting the timestamps in
		// backup files is the computer's local time.  The default is to use UTC
		// time.
		LocalTime bool `json:"localtime" yaml:"localtime"`

		// Compress determines if the rotated log files should be compressed
		// using gzip. The default is not to perform compression.
		Compress bool `json:"compress" yaml:"compress"`
	}
)

Functions

Package-level functions

Panicf, Fatalf, Errorf, Warnf, Infof, Debugf, Tracef

Dummy and Standard Logger

See the following codes:

import "github.com/hedzr/log"

var dummy, std log.Logger
func a(){
  // dummy Logger will discard any logging outputs
  dummy = log.NewDummyLogger()
  std = log.NewStdLoggerWith(log.OffLevel) // OffLevel is liks Dummy Logger
  std = log.NewStdLogger()
  
  std.Infof("slsl")
  
  print(std.GetLevel())
}
Utilities
Directory Helper

in exec/dir.go,

import "github.com/hedzr/log/exec"

func a(){
  print(exec.IsDiretory(exec.GetCurrentDir()))
  print(exec.GetExecutablePath())
  print(exec.GetExecutableDir())
}

IsRegularFile
FileExists
EnsureDir
EnsureDirEnh
NormalizeDir

_ = exec.ForDirMax(dir, 0, 1, func(depth int, cwd string, fi os.FileInfo) (stop bool, err error) {
	if fi.IsDir() {
		return
	}
      // ... doing something for a file,
	return
})

Exec Helpers
import "github.com/hedzr/log/exec"

exec.Run()
exec.Sudo()
exec.RunWithOutput()
exec.RunCommand()
exec.IsExitError()
exec.IsEAccess()
Trace Helpers
import "github.com/hedzr/log/trace"

trace.RegisterOnTraceModeChanges(handler)
trace.IsEnable()

trace.Start()
trace.Stop()

LICENSE

MIT

Documentation

Overview

Package log provide the standard interface of logging for what any go libraries want strip off the direct dependency from a known logging library.

Index

Constants

This section is empty.

Variables

AllLevels is a constant exposing all logging levels

Functions

func Debug added in v0.2.3

func Debug(args ...interface{})

Debug prints all args to stdin if logging level is greater than DebugLevel

func Debugf added in v0.1.16

func Debugf(msg string, args ...interface{})

Debugf prints the text to stdin if logging level is greater than DebugLevel

func Error added in v0.2.3

func Error(args ...interface{})

Error prints all args to stderr

func Errorf added in v0.1.16

func Errorf(msg string, args ...interface{})

Errorf prints the text to stderr

func Fatal added in v0.2.3

func Fatal(args ...interface{})

Fatal is equivalent to Printf() followed by a call to os.Exit(1).

func Fatalf added in v0.1.16

func Fatalf(msg string, args ...interface{})

Fatalf is equivalent to Printf() followed by a call to os.Exit(1).

func GetDebugMode added in v0.1.13

func GetDebugMode() bool

GetDebugMode return the debug boolean flag generally

func GetTraceMode added in v0.1.13

func GetTraceMode() bool

GetTraceMode return the trace boolean flag generally

func InDebugging added in v0.1.13

func InDebugging() bool

InDebugging check if the delve debugger presents

func InTesting added in v0.2.3

func InTesting() bool

InTesting detects whether is running under go test mode

func InTestingT added in v0.2.3

func InTestingT(args []string) bool

InTestingT detects whether is running under go test mode

func Info added in v0.2.3

func Info(args ...interface{})

Info prints all args to stdin if logging level is greater than InfoLevel

func Infof added in v0.1.16

func Infof(msg string, args ...interface{})

Infof prints the text to stdin if logging level is greater than InfoLevel

func Panic added in v0.2.3

func Panic(args ...interface{})

Panic is equivalent to Printf() followed by a call to panic().

func Panicf added in v0.1.16

func Panicf(msg string, args ...interface{})

Panicf is equivalent to Printf() followed by a call to panic().

func Print added in v0.2.3

func Print(args ...interface{})

Print calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Print.

func Printf added in v0.1.16

func Printf(msg string, args ...interface{})

Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.

func Println added in v0.2.3

func Println(args ...interface{})

Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println.

func SetDebugMode added in v0.1.13

func SetDebugMode(b bool)

SetDebugMode set the debug boolean flag generally

func SetLevel added in v0.1.16

func SetLevel(l Level)

SetLevel sets the logging level

func SetLogger added in v0.1.17

func SetLogger(l Logger)

SetLogger transfer an instance into log package-level value

func SetOutput added in v0.3.1

func SetOutput(w io.Writer)

SetOutput setup the logging output device

func SetTraceMode added in v0.1.13

func SetTraceMode(b bool)

SetTraceMode set the trace boolean flag generally

func Trace added in v0.2.3

func Trace(args ...interface{})

Trace prints all args to stdin if logging level is greater than TraceLevel

func Tracef added in v0.1.16

func Tracef(msg string, args ...interface{})

Tracef prints the text to stdin if logging level is greater than TraceLevel

func Warn added in v0.2.3

func Warn(args ...interface{})

Warn prints all args to stderr

func Warnf added in v0.1.16

func Warnf(msg string, args ...interface{})

Warnf prints the text to stderr

Types

type CmdrMinimal added in v0.1.13

type CmdrMinimal interface {
	InDebugging() bool
	GetDebugMode() bool
	GetTraceMode() bool
	SetDebugMode(b bool)
	SetTraceMode(b bool)
}

CmdrMinimal provides the accessors to debug/trace flags

func MinimalEnv added in v0.1.13

func MinimalEnv() CmdrMinimal

MinimalEnv return the Env/CmdrMinimal object

type Env added in v0.1.13

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

Env structure holds the debug/trace flags and provides CmdrMinimal accessors

func (*Env) GetDebugMode added in v0.1.13

func (e *Env) GetDebugMode() bool

GetDebugMode return the debug boolean flag generally

func (*Env) GetTraceMode added in v0.1.13

func (e *Env) GetTraceMode() bool

GetTraceMode return the trace boolean flag generally

func (*Env) InDebugging added in v0.1.13

func (e *Env) InDebugging() bool

InDebugging check if the delve debugger presents

func (*Env) SetDebugMode added in v0.1.13

func (e *Env) SetDebugMode(b bool)

SetDebugMode set the debug boolean flag generally

func (*Env) SetTraceMode added in v0.1.13

func (e *Env) SetTraceMode(b bool)

SetTraceMode set the trace boolean flag generally

type L added in v0.2.3

type L interface {
	// Trace prints all args to stdin if logging level is greater than TraceLevel
	Trace(args ...interface{})
	// Debug prints all args to stdin if logging level is greater than DebugLevel
	Debug(args ...interface{})
	// Info prints all args to stdin if logging level is greater than InfoLevel
	Info(args ...interface{})
	// Warn prints all args to stderr
	Warn(args ...interface{})
	// Error prints all args to stderr
	Error(args ...interface{})
	// Fatal is equivalent to Printf() followed by a call to os.Exit(1).
	Fatal(args ...interface{})
	// Panic is equivalent to Printf() followed by a call to panic().
	Panic(args ...interface{})
	// Print calls Output to print to the standard logger.
	// Arguments are handled in the manner of fmt.Print.
	Print(args ...interface{})
	// Println calls Output to print to the standard logger.
	// Arguments are handled in the manner of fmt.Println.
	Println(args ...interface{})
}

func AsL added in v0.2.3

func AsL(logger LF) L

AsL converts a logger to L type (with Info(...), ... prototypes)

type LF added in v0.2.3

type LF interface {
	// Tracef prints the text to stdin if logging level is greater than TraceLevel
	Tracef(msg string, args ...interface{})
	// Debugf prints the text to stdin if logging level is greater than DebugLevel
	Debugf(msg string, args ...interface{})
	// Infof prints the text to stdin if logging level is greater than InfoLevel
	Infof(msg string, args ...interface{})
	// Warnf prints the text to stderr
	Warnf(msg string, args ...interface{})
	// Errorf prints the text to stderr
	Errorf(msg string, args ...interface{})
	// Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
	Fatalf(msg string, args ...interface{})
	// Panicf is equivalent to Printf() followed by a call to panic().
	Panicf(msg string, args ...interface{})
	// Printf calls Output to print to the standard logger.
	// Arguments are handled in the manner of fmt.Printf.
	Printf(msg string, args ...interface{})
}

type Level

type Level uint32

Level type

const (
	// PanicLevel level, highest level of severity. Logs and then calls panic with the
	// message passed to Debug, Info, ...
	PanicLevel Level = iota
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
	// logging level is set to Panic.
	FatalLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
	// TraceLevel level. Designates finer-grained informational events than the Debug.
	TraceLevel
	// OffLevel level. The logger will be shutdown.
	OffLevel
)

These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `logrus.New()`.

func GetLevel added in v0.1.16

func GetLevel() Level

GetLevel returns the current logging level

func ParseLevel

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the Logrus log level constant.

func (Level) MarshalText

func (level Level) MarshalText() ([]byte, error)

MarshalText convert Level to string and []byte

func (Level) String

func (level Level) String() string

Convert the Level to a string. E.g. PanicLevel becomes "panic".

func (*Level) UnmarshalText

func (level *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Logger

type Logger interface {
	LF

	// SetLevel sets the logging level
	SetLevel(lvl Level)
	// GetLevel returns the current logging level
	GetLevel() Level
	// SetOutput setup the logging output device
	SetOutput(out io.Writer)
	// SetOutput returns the current logging output device
	GetOutput() (out io.Writer)

	// Setup will be invoked once an instance created
	Setup()

	// AddSkip adds an extra count to skip stack frames
	AddSkip(skip int) Logger
}

Logger is a minimal logger with no more dependencies

func AsLogger added in v0.2.3

func AsLogger(logger L) Logger

AsLogger converts a logger to LF or Logger type (with Infof(...), ... prototypes)

func GetLogger added in v0.1.17

func GetLogger() Logger

GetLogger returns the package-level logger globally

func NewDummyLogger added in v0.1.5

func NewDummyLogger() Logger

NewDummyLogger return a dummy logger

func NewStdLogger added in v0.1.7

func NewStdLogger() Logger

NewStdLogger return a stdlib `log` logger

func NewStdLoggerWith added in v0.1.18

func NewStdLoggerWith(lvl Level) Logger

NewStdLoggerWith return a stdlib `log` logger

type LoggerConfig

type LoggerConfig struct {
	Enabled          bool
	Backend          string // zap, sugar, logrus
	Level            string // level
	Format           string // text, json, ...
	Target           string // console, file, console+file
	Directory        string // logdir, for file
	AllToErrorDevice bool   //
	DebugMode        bool   `json:"-" yaml:"-"`
	TraceMode        bool   `json:"-" yaml:"-"`

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int `json:"maxsize" yaml:"maxsize"`

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int `json:"maxage" yaml:"maxage"`

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool `json:"localtime" yaml:"localtime"`

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"`
}

LoggerConfig is used for creating a minimal logger with no more dependencies

func NewLoggerConfig

func NewLoggerConfig() *LoggerConfig

NewLoggerConfig returns a default LoggerConfig

func NewLoggerConfigWith added in v0.1.17

func NewLoggerConfigWith(enabled bool, backend, level string) *LoggerConfig

NewLoggerConfigWith returns a default LoggerConfig

type LoggerExt added in v0.2.3

type LoggerExt interface {
	L
	Logger
}

LoggerExt is a minimal logger with no more dependencies

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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