lg

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2023 License: Apache-2.0 Imports: 25 Imported by: 0

README

Logging helper

Basic

There are four levels of logs:

  • INFO: Normal processing log message. Sink: stdout
  • ERROR: Recoverable error log message. Sink: stderr
  • DEBUG: Misc log message. Only enable when debug mode is on. Sink: stdout
  • FATAL: Unrecoverable error log message. It will panic the application. It should only be triggered for any error caused by Non-user input. Sink: stderr

Methods

Multiple logging interfaces are provided in this lg package:

  • {{Level}}(v ...interface{}): The simplest method to log one or more strings/variables.
  • {{Level}}f(format string, v ...interface{}): Format the log with c-style printf format.
  • {{Level}}c(ctx context.Context, format string, v ...interface{}): This method accept a log context to inherit parameters from parent With() output.
  • With(ctx context.Context, format string, v ...interface{}): This method writes no actual log. Instead, it returns a log context for ancestor application.

Best practice

It's best for log analyser, like Kibana/ElasticSearch, to process structure data Ref.

You are suggested to use Xxxc() series( Infoc, Errorc etc.) logging method to write log. The format string should compose multiple pairs of key/value paramters, like name=%s price=%.2f, with = between key and value descriptor.

Example:

func Somefunc(ctx context.Context, in *pb.Request) (*pb.Reply, error) {
    ctx = lg.With(ctx, "board_id=%s user_id=%s", in.GetBoardId(), in.GetUserId())

    // Do actual logic ...
    lg.Infoc(ctx, "Done")
    // Output:
    // [INFO]2019/07/02 07:25:51 Done board_id=12345 user_id=67890
}

Timezone

Beware! The log record will be logged in UTC timezone, instead of China +0800. This is designed to fit our applications into datacenters in different timezones.

Production deployment

(No mandatory right now) To deploy applications to production environment, it would be better to set JSON output encoding with lg.SetEncoding(lg.TypeJSON), so that the filebeat can automatically collected the structured log, and help analysis.

Documentation

Index

Constants

View Source
const SlowPrefix = "!SLOW! "

Variables

This section is empty.

Functions

func DPanicError

func DPanicError(err error)

DPanicError provide a quick way to check unexpected errors that should never happen. It's almost the same as Check(), except only in debug mode will throw panic.

func Debug

func Debug(v ...interface{})

Debug prints info to standard output with [DEBUG] prefix in debug mode.

func Debugc

func Debugc(ctx context.Context, msg string, v ...interface{})

Debugc logs debug message in logfmt.

func Debugf

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

Debugf except accepting formating info.

func Derive

func Derive(src, dest context.Context) context.Context

Derive extracts log context from src context, to merge it into dest context.

func EnableDebug

func EnableDebug()

EnableDebug ...

func Error

func Error(v ...interface{})

Error prints error to error output with [ERROR] prefix.

func Errorc

func Errorc(ctx context.Context, msg string, v ...interface{})

Errorc logs error message in logfmt.

func Errorf

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

Errorf except accepting formating info.

func Fatal

func Fatal(v ...interface{})

Fatal prints error to error output with [FATAL] prefix, and terminate the application.

func Fatalc

func Fatalc(ctx context.Context, msg string, v ...interface{})

Fatalc logs debug message in logfmt. see `Fatal()` for more detail.

func Fatalf

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

Fatalf except accepting formating info.

func ForkLog

func ForkLog(tailBytes int) io.ReadCloser

func GetFuncName

func GetFuncName(i interface{}) string

GetFuncName provides shortcut to print the name of any function.

func Info

func Info(v ...interface{})

Info prints info to standard output with [INFO] prefix.

func Infoc

func Infoc(ctx context.Context, msg string, v ...interface{})

Infoc logs message in logfmt.

func Infof

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

Infof except accepting formating info.

func InterceptLogs

func InterceptLogs(w io.Writer) io.Writer

func IsDebugging

func IsDebugging() bool

IsDebugging returns whether it's in debug mode.

func Jsonify

func Jsonify(v interface{}) string

Jsonify provides shortcut to return an json format string of any varible.

func JsonifyNested

func JsonifyNested(v interface{}) string

func PanicError

func PanicError(err error, msg ...interface{})

PanicError provide a quick way to check unexpected errors that should never happen. It's basically an assertion that once err != nil, fatal panic is thrown.

func PrintJSON

func PrintJSON(v interface{})

PrintJSON outputs any varible in JSON format to console. Useful for debuging.

func PrintJSONc

func PrintJSONc(ctx context.Context, v interface{})

PrintJSONc outputs any varible in JSON format to console, and logger within context. Useful for debuging.

func SetEncoding

func SetEncoding(t EncodingType)

SetEncoding changes the log encoding type.

func StreamClientInterceptor

func StreamClientInterceptor(from string) func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error)

StreamClientInterceptor injects log context into outgoing grpc request.

func StreamServerInterceptor

func StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error

StreamServerInterceptor retrieve log context from incoming grpc request.

func TimeDebugc

func TimeDebugc(ctx context.Context, msg string, v ...interface{}) func()

func TimeFunc

func TimeFunc(v ...interface{}) func()

TimeFunc prints the info with timing consumed by function. It has specified usage like:

defer TimeFunc("Hello world")()

func TimeFuncDebug

func TimeFuncDebug(v ...interface{}) func()

func TimeFuncDuration

func TimeFuncDuration() func() time.Duration

TimeFuncDuration returns the duration consumed by function. It has specified usage like:

    f := TimeFuncDuration()
	   DoSomething()
	   duration := f()

func TimeInfoc

func TimeInfoc(ctx context.Context, msg string, v ...interface{}) func()

func TimeInfocSlow

func TimeInfocSlow(ctx context.Context, slowDuration time.Duration, msg string, v ...interface{}) func()

TimeInfocSlow prints the info with timing consumed by function. If the cost is larger than slowDuration, it will be printed with !SLOW! prefix before msg.

func UnaryClientInterceptor

func UnaryClientInterceptor(from string) func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error

UnaryClientInterceptor injects log context into outgoing grpc request.

func UnaryServerInterceptor

func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

UnaryServerInterceptor retrieve log context from incoming grpc request.

func Warn

func Warn(v ...interface{})

Warn prints warn to warn output with [WARN] prefix.

func Warnc

func Warnc(ctx context.Context, msg string, v ...interface{})

Warnc logs warn message in logfmt.

func Warnf

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

Warnf except accepting formating info.

func With

func With(ctx context.Context, msg string, v ...interface{}) context.Context

With wraps a new context, ands inject log context messge into it.

func WithKV

func WithKV(ctx context.Context, key string, val interface{}) context.Context

WithKV returns a copy of ctx, which will print "{key}={val}" with the log when use methods like Infoc()

func WithLogger

func WithLogger(ctx context.Context, w io.Writer) context.Context

Types

type EncodingType

type EncodingType string

EncodingType represent the type to use for log encoding.

const (
	// TypeJSON encodes log into one-line json.
	TypeJSON EncodingType = "json"

	// TypeLogfmt encodes log into logfmt(structlog) format.
	TypeLogfmt EncodingType = "logfmt"
)

type LogContext

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

LogContext indicates all the contextual logs in a request.

func FromContext

func FromContext(ctx context.Context) *LogContext

FromContext returns a the potential LogContext object from Context if any.

func (*LogContext) Empty

func (lc *LogContext) Empty() bool

Empty returns true if the log context contains nothing.

func (*LogContext) From

func (lc *LogContext) From() string

func (*LogContext) JSON

func (lc *LogContext) JSON() string

JSON returns the log in JSON format.

func (*LogContext) Logfmt

func (lc *LogContext) Logfmt(enableColor bool) string

Logfmt returns the log in LOGFMT format.

func (*LogContext) Map

func (lc *LogContext) Map() map[string]string

func (*LogContext) Message

func (lc *LogContext) Message() string

func (*LogContext) Since

func (lc *LogContext) Since() time.Time

func (*LogContext) String

func (lc *LogContext) String() string

String returns a string representing the log.

func (*LogContext) UUID

func (lc *LogContext) UUID() int64

type Span

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

type StripColorReader

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

func NewStripColorReader

func NewStripColorReader(r io.Reader) *StripColorReader

func (*StripColorReader) Read

func (scr *StripColorReader) Read(p []byte) (int, error)

type StripColorWriter

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

func NewStripColorWriter

func NewStripColorWriter(w io.Writer) *StripColorWriter

func (*StripColorWriter) Write

func (scw *StripColorWriter) Write(p []byte) (int, error)

type StripPrefixReader

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

func NewStripPrefixReader

func NewStripPrefixReader(r io.Reader, prefix []byte) *StripPrefixReader

func (*StripPrefixReader) Read

func (scr *StripPrefixReader) Read(p []byte) (int, error)

type Terminal

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

func NewTerminal

func NewTerminal(maxBufSize int) *Terminal

func (*Terminal) ForkTTY

func (t *Terminal) ForkTTY(tailBytes int) *tty

func (*Terminal) Write

func (t *Terminal) Write(p []byte) (int, error)

type Timer

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

Timer is a helper to time multiple tick. Simple usage like: ``` t := lg.NewTimer("Search similar", itemID) defer lg.Info(t) meta := getMeta(itemID) t.Tick("Get meta") results := querySimilar(itemID) t.Tick("Query") return formatResult(results) ```

func NewTimer

func NewTimer(msg ...interface{}) *Timer

NewTimer returns a Timer object.

func (*Timer) Duration

func (t *Timer) Duration() time.Duration

func (*Timer) String

func (t *Timer) String() string

func (*Timer) SubTimer

func (t *Timer) SubTimer(msg ...interface{}) *Timer

SubTimer starts a new timer whose data returns to its parent timer.

func (*Timer) Tick

func (t *Timer) Tick(msg ...interface{})

Tick records the time ecaplsed since start of timer.

Jump to

Keyboard shortcuts

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