logger

package
v0.0.0-...-d31700d Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2022 License: MIT Imports: 12 Imported by: 0

README

logger

a logger that integrate with alarm.

Usage

logger := New(os.Stdout)

logger.SetLevel(Debug)
logger.Debug("the ", "message")
logger.Debugf("this is %s", "test")

logger.Info("the ", "message")
logger.Infof("this is a %s", "test")

logger.Error("err")
logger.Errorf("test %s", "errorf")

logger.Panic("panic !!")
logger.Panicf("test %s", "panicf")

logger.Fatal("fatal !!")
logger.Fatalf("test %s", "fatalf")

defer logger.Recover()

logger.Record(func(ctx context.Context) error {
  // work to do goes here
  return nil
}, nil, func(f *Fields) {
  f.With("key1", "value1").With("key2", "value2")
})

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrintJson

func PrintJson(v interface{})

Types

type Alarm

type Alarm interface {
	Send(title, content string)
	Alarm(title, content, mergeKey string)
}

type Fields

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

func (*Fields) Debug

func (f *Fields) Debug(args ...interface{}) bool
Example
writer := bytes.NewBuffer(nil)
New(writer).SetLevel(Debug).With("key", "value").With("key2", "value2").Debug(`the `, `message`)
fmt.Println(strings.HasSuffix(writer.String(),
	`,"key":"value","key2":"value2","level":"debug",`+machineName+`"msg":"the message"}
`))
Output:

true

func (*Fields) Debugf

func (f *Fields) Debugf(format string, args ...interface{})
Example
writer := bytes.NewBuffer(nil)
New(writer).SetLevel(Debug).With("key", "value").With("key2", "value2").
	Debugf("%s %s", `the`, `message`)
fmt.Println(strings.HasSuffix(writer.String(),
	`,"key":"value","key2":"value2","level":"debug",`+machineName+`"msg":"the message"}
`))
Output:

true

func (*Fields) Error

func (f *Fields) Error(args ...interface{})
Example
writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Error(`the `, `message`)
fmt.Println(strings.Contains(writer.String(),
	`,"key":"value","key2":"value2","level":"error",`+machineName+`"msg":"the message",`+
		`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Error\n\t`,
))
Output:

true

func (*Fields) Errorf

func (f *Fields) Errorf(format string, args ...interface{})
Example
writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Errorf("%s %s", `the`, `message`)
fmt.Println(strings.Contains(writer.String(),
	`,"key":"value","key2":"value2","level":"error",`+machineName+`"msg":"the message",`+
		`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Errorf\n\t`,
))
Output:

true

func (*Fields) Fatal

func (f *Fields) Fatal(args ...interface{})
Example
var exitStatus int
exitFunc = func(status int) { exitStatus = status }
defer func() { exitFunc = os.Exit }()

writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Fatal("the message")
if exitStatus != 1 {
	fmt.Printf("unexpected exit status: %d", exitStatus)
	return
}
fmt.Println(strings.Contains(writer.String(),
	`,"key":"value","key2":"value2","level":"fatal",`+machineName+`"msg":"the message",`+
		`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Fatal\n\t`,
))
Output:

true

func (*Fields) Fatalf

func (f *Fields) Fatalf(format string, args ...interface{})
Example
var exitStatus int
exitFunc = func(status int) { exitStatus = status }
defer func() { exitFunc = os.Exit }()

writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Fatalf("%s %s", "the", "message")
if exitStatus != 1 {
	fmt.Printf("unexpected exit status: %d", exitStatus)
	return
}
fmt.Println(strings.Contains(writer.String(),
	`,"key":"value","key2":"value2","level":"fatal",`+machineName+`"msg":"the message",`+
		`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Fatalf\n\t`,
))
Output:

true

func (*Fields) Info

func (f *Fields) Info(args ...interface{}) bool
Example
writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Info(`the `, `message`)
fmt.Println(strings.HasSuffix(writer.String(),
	`,"key":"value","key2":"value2","level":"info",`+machineName+`"msg":"the message"}
`))
Output:

true

func (*Fields) Infof

func (f *Fields) Infof(format string, args ...interface{})
Example
writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Infof("%s %s", `the`, `message`)
fmt.Println(strings.HasSuffix(writer.String(),
	`,"key":"value","key2":"value2","level":"info",`+machineName+`"msg":"the message"}
`))
Output:

true

func (*Fields) Panic

func (f *Fields) Panic(args ...interface{})
Example
writer := bytes.NewBuffer(nil)
defer func() {
	err := recover()
	if err != "the message" {
		fmt.Printf("unexpected err: %v", err)
		return
	}
	fmt.Println(strings.Contains(writer.String(),
		`,"key":"value","key2":"value2","level":"panic",`+machineName+`"msg":"the message",`+
			`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Panic\n\t`,
	))
}()
New(writer).With("key", "value").With("key2", "value2").Panic("the message")
Output:

true

func (*Fields) Panicf

func (f *Fields) Panicf(format string, args ...interface{})
Example
writer := bytes.NewBuffer(nil)
defer func() {
	err := recover()
	if err != "the message" {
		fmt.Printf("unexpected err: %v", err)
		return
	}
	fmt.Println(strings.Contains(writer.String(),
		`,"key":"value","key2":"value2","level":"panic",`+machineName+`"msg":"the message",`+
			`"stack":"gitee.com/go-better/dev/debug/logger.ExampleFields_Panicf\n\t`,
	))
}()
New(writer).With("key", "value").With("key2", "value2").Panicf("%s %s", "the", "message")
Output:

true

func (*Fields) Recover

func (f *Fields) Recover()
Example
writer := bytes.NewBuffer(nil)
func() {
	defer New(writer).With("key", "value").With("key2", "value2").Recover()
	panic("the message")
}()
fmt.Println(strings.Contains(writer.String(),
	`,"key":"value","key2":"value2","level":"recover",`+machineName+`"msg":"the message",`+
		`"stack":"gitee.com/go-better/dev/debug/logger.(*Fields).Recover\n\t`,
))
Output:

true

func (*Fields) With

func (f *Fields) With(key string, value interface{}) *Fields

don't use (level, at, msg, stack, duration) as key, they will be overwritten.

Example
writer := bytes.NewBuffer(nil)
New(writer).With("key", "value").With("key2", "value2").Info(`the `, `message`)
str := writer.String()
fmt.Println(strings.HasSuffix(
	str, `,"key":"value","key2":"value2","level":"info",`+machineName+`"msg":"the message"}
`))
Output:

true

type Formatter

type Formatter interface {
	Format(map[string]interface{}) ([]byte, error)
}

type Level

type Level int8
const (
	Fatal Level = iota
	Panic
	Recover
	Error
	Info
	Debug
)

func (Level) String

func (l Level) String() string
Example
var l Level
l = 10
fmt.Println(l.String())
// Ouput: invalid
Output:

type Logger

type Logger struct {
	// contains filtered or unexported fields
}
Example (DoAlarm_1)
writer, alarm := bytes.NewBuffer(nil), &testAlarm{}
logger := New(writer)
logger.SetAlarm(alarm)
logger.doAlarm(Panic, nil)
fmt.Println(alarm.title, alarm.content)
Output:

null
Example (DoAlarm_2)
writer := bytes.NewBuffer(nil)
logger := New(writer)
var mapIn = make(map[interface{}]interface{})
logger.doAlarm(Panic, map[string]interface{}{"test": mapIn})
fmt.Println(strings.Contains(writer.String(),
	`"level":"error",`+machineName+`"msg":"logger format: json: unsupported type: map[interface {}]interface {}`,
))
Output:

true
Example (Format_1)
writer, alarm := bytes.NewBuffer(nil), &testAlarm{}
logger := New(writer)
logger.SetAlarm(alarm)
fmt.Println(string(logger.format(map[string]interface{}{"key": true}, true)))
Output:

{
  "key": true
}
Example (Format_2)
writer := bytes.NewBuffer(nil)
logger := New(writer)
var testIn = make(map[interface{}]interface{})
var fields = make(map[string]interface{})
fields[`key`] = testIn
fmt.Println(logger.format(fields, true) == nil)
Output:

true
Example (GetFields_1)
writer := bytes.NewBuffer(nil)
logger := New(writer)
logger.fields = map[string]interface{}{"key": true, "key1": "value1"}
got := logger.getFields(Recover, "message", nil)
fmt.Println(got[`level`], got[`msg`], got[`key`], got[`key1`])
Output:

recover message true value1
Example (Output)
New(os.Stderr).output(Info, "", nil)
Output:

Example (Output_1)
writer := bytes.NewBuffer(nil)
New(writer).SetPid().output(Info, "message", map[string]interface{}{"key": "value"})
expect := fmt.Sprintf(`,"key":"value","level":"info",`+machineName+`"msg":"message","pid":%d}`, os.Getpid())
fmt.Println(strings.Contains(writer.String(), expect))
Output:

true
Example (Output_2)
writer := bytes.NewBuffer(nil)
New(writer).output(Error, "message", map[string]interface{}{"key": "value"})
fmt.Println(strings.Contains(writer.String(), `,"key":"value","level":"error",`+machineName+`"msg":"message"}`))
Output:

true
Example (Output_3)
writer := bytes.NewBuffer(nil)
logger := New(writer)
logger.writer = os.Stderr
logger.output(Panic, "message", map[string]interface{}{"key": "value"})
fmt.Println(writer.String())
Output:

func New

func New(writer io.Writer) *Logger
Example
log := New(nil)
fmt.Println(log.writer == os.Stderr)
Output:

true

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{}) bool

func (*Logger) Debugf

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

func (*Logger) Error

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

func (*Logger) Errorf

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

func (*Logger) Fatal

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

func (*Logger) Fatalf

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

func (*Logger) Info

func (l *Logger) Info(args ...interface{}) bool

func (*Logger) Infof

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

func (*Logger) Panic

func (l *Logger) Panic(args ...interface{})

func (*Logger) Panicf

func (l *Logger) Panicf(format string, args ...interface{})

func (*Logger) Record

func (l *Logger) Record(
	workFunc func(context.Context) error, recoverFunc func(), fieldsFunc func(*Fields),
)

func (*Logger) RecordWithContext

func (l *Logger) RecordWithContext(ctx context.Context,
	workFunc func(context.Context) error, recoverFunc func(), fieldsFunc func(*Fields),
)

func (*Logger) Recover

func (l *Logger) Recover()

func (*Logger) Set

func (l *Logger) Set(key string, value interface{}) *Logger

Set a default field by key and value. Don't use "level", "at", "msg", "stack", "duration" they will be overwritten.

func (*Logger) SetAlarm

func (l *Logger) SetAlarm(alarm Alarm) *Logger

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level) *Logger
Example
logger := New(nil)
logger.SetLevel(Panic)
fmt.Println(logger.level)

var level Level = 10
logger.SetLevel(level)
fmt.Println(logger.level)

logger.SetLevel(Info)
fmt.Println(logger.level)

// Ouput:
// panic
// debug
// info
Output:

func (*Logger) SetMachineIP

func (l *Logger) SetMachineIP() *Logger

Set a default ip field

func (*Logger) SetPid

func (l *Logger) SetPid() *Logger

Set a default pid field

func (*Logger) With

func (l *Logger) With(key string, value interface{}) *Fields

don't use (level, at, msg, stack, duration) as key, they will be overwritten.

func (*Logger) WithTracer

func (l *Logger) WithTracer(t *tracer.Tracer) *Fields
Example
logger := New(nil)
var t = &tracer.Tracer{
	At:       time.Now(),
	Children: []*tracer.Tracer{{At: time.Now()}},
	Tags:     map[string]interface{}{"key": "value"},
	Logs:     []string{"the message"},
}
got := logger.WithTracer(t)

expect := &Fields{
	Logger: logger,
	data: map[string]interface{}{
		"at": t.At, "duration": t.Duration,
		"children": t.Children, "tags": t.Tags,
		"logs": []string{"the message"},
	},
}
fmt.Println(reflect.DeepEqual(got, expect))
Output:

true

Jump to

Keyboard shortcuts

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