pax_global_header00006660000000000000000000000064142312464170014516gustar00rootroot0000000000000052 comment=2f95bdde8c3c97bfbf6d016fcc410669a895b9e7 logex-1.2.1/000077500000000000000000000000001423124641700126355ustar00rootroot00000000000000logex-1.2.1/.travis.yml000066400000000000000000000000151423124641700147420ustar00rootroot00000000000000language: go logex-1.2.1/LICENSE000066400000000000000000000020621423124641700136420ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Chzyer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. logex-1.2.1/Makefile000066400000000000000000000000641423124641700142750ustar00rootroot00000000000000test: go test -v ./... install: go install ./... logex-1.2.1/README.md000066400000000000000000000042111423124641700141120ustar00rootroot00000000000000Logex ======= [![Build Status](https://travis-ci.org/chzyer/logex.svg?branch=master)](https://travis-ci.org/chzyer/logex) [![GoDoc](https://godoc.org/github.com/chzyer/logex?status.svg)](https://godoc.org/github.com/chzyer/logex) An golang log lib, supports tracing and level, wrap by standard log lib How To Get ======= shell ``` go get github.com/chzyer/logex ``` source code ```{go} import "github.com/chzyer/logex" // package name is logex func main() { logex.Info("Hello!") } ``` Level ======= ```{go} import "github.com/chzyer/logex" func main() { logex.Println("") logex.Debug("debug staff.") // Only show if has an "DEBUG" named env variable(whatever value). logex.Info("info") logex.Warn("") logex.Fatal("") // also trigger exec "os.Exit(1)" logex.Error(err) // print error logex.Struct(obj) // print objs follow such layout "%T(%+v)" logex.Pretty(obj) // print objs as JSON-style, more readable and hide non-publish properties, just JSON } ``` Extendability ====== source code ```{go} type MyStruct struct { BiteMe bool } ``` may change to ```{go} type MyStruct struct { BiteMe bool logex.Logger // just this } func main() { ms := new(MyStruct) ms.Info("woo!") } ``` Runtime Tracing ====== All log will attach theirs stack info. Stack Info will shown by an layout, `{packageName}.{FuncName}:{FileName}:{FileLine}` ```{go} package main import "github.com/chzyer/logex" func test() { logex.Pretty("hello") } func main() { test() } ``` response ``` 2014/10/10 15:17:14 [main.test:testlog.go:6][PRETTY] "hello" ``` Error Tracing ====== You can trace an error if you want. ```{go} package main import ( "github.com/chzyer/logex" "os" ) func openfile() (*os.File, error) { f, err := os.Open("xxx") if err != nil { err = logex.Trace(err) } return f, err } func test() error { f, err := openfile() if err != nil { return logex.Trace(err) } f.Close() return nil } func main() { err := test() if err != nil { logex.Error(err) return } logex.Info("test success") } ``` response ``` 2014/10/10 15:22:29 [main.main:testlog.go:28][ERROR] [main.openfile:11;main.test:19] open xxx: no such file or directory ``` logex-1.2.1/err.go000066400000000000000000000065361423124641700137660ustar00rootroot00000000000000package logex import ( "bytes" "errors" "fmt" "path" "runtime" "strconv" "strings" ) func Define(info string) *traceError { return &traceError{ error: errors.New(info), } } func NewError(info ...interface{}) *traceError { return TraceEx(1, errors.New(sprint(info))) } func NewErrorf(format string, info ...interface{}) *traceError { return TraceEx(1, errors.New(sprintf(format, info))) } func EqualAny(e error, es []error) bool { for i := 0; i < len(es); i++ { if Equal(e, es[i]) { return true } } return false } func Equal(e1, e2 error) bool { if e, ok := e1.(*traceError); ok { e1 = e.error } if e, ok := e2.(*traceError); ok { e2 = e.error } return e1 == e2 } type traceError struct { error format []interface{} stack []string code *int } func (t *traceError) SetCode(code int) *traceError { if t.stack == nil { t = TraceEx(1, t) } t.code = &code return t } func (t *traceError) GetCode() int { if t.code == nil { return 500 } return *t.code } func (t *traceError) Error() string { if t == nil { return "" } if t.format == nil { if t.error == nil { panic(t.stack) } return t.error.Error() } return fmt.Sprintf(t.error.Error(), t.format...) } func (t *traceError) Trace(info ...interface{}) *traceError { return TraceEx(1, t, info...) } func (t *traceError) Follow(err error) *traceError { if t == nil { return nil } if te, ok := err.(*traceError); ok { if len(te.stack) > 0 { te.stack[len(te.stack)-1] += ":" + err.Error() } t.stack = append(te.stack, t.stack...) } return t } func (t *traceError) Format(obj ...interface{}) *traceError { if t.stack == nil { t = TraceEx(1, t) } t.format = obj return t } func (t *traceError) StackError() string { if t == nil { return t.Error() } if len(t.stack) == 0 { return t.Error() } return fmt.Sprintf("[%s] %s", strings.Join(t.stack, ";"), t.Error()) } func Tracefmt(layout string, objs ...interface{}) error { var teInfo *traceError for idx, obj := range objs { if te, ok := obj.(*traceError); ok { teInfo = te objs[idx] = te.Error() } } return &traceError{ error: fmt.Errorf(layout, objs...), format: teInfo.format, stack: teInfo.stack, code: teInfo.code, } } func Tracef(err error, obj ...interface{}) *traceError { e := TraceEx(1, err).Format(obj...) return e } // set runtime info to error func TraceError(err error, info ...interface{}) *traceError { return TraceEx(1, err, info...) } func Trace(err error, info ...interface{}) error { if err == nil { return nil } return TraceEx(1, err, info...) } func joinInterface(info []interface{}, ch string) string { ret := bytes.NewBuffer(make([]byte, 0, 512)) for idx, o := range info { if idx > 0 { ret.WriteString(ch) } ret.WriteString(fmt.Sprint(o)) } return ret.String() } func TraceEx(depth int, err error, info ...interface{}) *traceError { if err == nil { return nil } pc, _, line, _ := runtime.Caller(1 + depth) name := runtime.FuncForPC(pc).Name() name = path.Base(name) stack := name + ":" + strconv.Itoa(line) if len(info) > 0 { stack += "(" + joinInterface(info, ",") + ")" } if te, ok := err.(*traceError); ok { if te.stack == nil { // define return &traceError{ error: te.error, stack: []string{stack}, } } te.stack = append(te.stack, stack) return te } return &traceError{err, nil, []string{stack}, nil} } logex-1.2.1/err_test.go000066400000000000000000000010061423124641700150100ustar00rootroot00000000000000package logex import ( "os" "strings" "testing" ) func b() error { _, err := os.Open("dflkjasldfkas") return Trace(err) } func a() error { return Trace(b()) } func TestError(t *testing.T) { te := TraceError(a()) errInfo := te.StackError() prefixes := []string{"logex%2ev1", "logex"} for _, p := range prefixes { if strings.Contains(errInfo, p+".b:11") && strings.Contains(errInfo, p+".a:15") && strings.Contains(errInfo, p+".TestError:19") { return } } t.Error("fail", te.StackError()) } logex-1.2.1/go.mod000066400000000000000000000000501423124641700137360ustar00rootroot00000000000000module github.com/chzyer/logex go 1.15 logex-1.2.1/logex.go000066400000000000000000000124131423124641700143030ustar00rootroot00000000000000package logex import ( "encoding/json" "fmt" "io" goLog "log" "os" "path" "runtime" "strconv" "strings" ) var DebugLevel = 1 type Logger struct { depth int reqid string Logger *goLog.Logger } func NewLogger(l int) *Logger { return &Logger{l, "", goLogStd} } func NewLoggerEx(w io.Writer) *Logger { return &Logger{0, "", NewGoLog(w)} } func NewGoLog(w io.Writer) *goLog.Logger { return goLog.New(w, "", goLog.LstdFlags) } var goLogStd = goLog.New(os.Stderr, "", goLog.LstdFlags) var std = NewLogger(0) var ShowCode = true var ( Println = std.Println Infof = std.Infof Info = std.Info Debug = std.Debug Debugf = std.Debugf Error = std.Error Errorf = std.Errorf Warn = std.Warn PrintStack = std.PrintStack Stack = std.Stack Panic = std.Panic Fatal = std.Fatal Struct = std.Struct Pretty = std.Pretty Todo = std.Todo ) func SetStd(l *Logger) { std = l Println = std.Println Infof = std.Infof Info = std.Info Debug = std.Debug Error = std.Error Warn = std.Warn PrintStack = std.PrintStack Stack = std.Stack Panic = std.Panic Fatal = std.Fatal Struct = std.Struct Pretty = std.Pretty Todo = std.Todo } var ( INFO = "[INFO] " ERROR = "[ERROR] " PANIC = "[PANIC] " DEBUG = "[DEBUG] " WARN = "[WARN] " FATAL = "[FATAL] " STRUCT = "[STRUCT] " PRETTY = "[PRETTY] " TODO = "[TODO] " ) func color(col, s string) string { if col == "" { return s } return "\x1b[0;" + col + "m" + s + "\x1b[0m" } func init() { if os.Getenv("DEBUG") != "" { DebugLevel = 0 ERROR = color("32", ERROR) } } func DownLevel(i int) Logger { return std.DownLevel(i - 1) } // decide to show which level's stack func (l Logger) DownLevel(i int) Logger { return Logger{l.depth + i, l.reqid, l.Logger} } // output objects to json format func (l Logger) Pretty(os ...interface{}) { content := "" for i := range os { if ret, err := json.MarshalIndent(os[i], "", "\t"); err == nil { content += string(ret) + "\n" } } l.Output(2, PRETTY+content) } // just print func (l Logger) Print(o ...interface{}) { l.Output(2, sprint(o)) } // just print by format func (l Logger) Printf(layout string, o ...interface{}) { l.Output(2, sprintf(layout, o)) } // just println func (l Logger) Println(o ...interface{}) { l.Output(2, " "+sprint(o)) } func (l Logger) Info(o ...interface{}) { if DebugLevel > 1 { return } l.Output(2, INFO+sprint(o)) } func (l Logger) Infof(f string, o ...interface{}) { if DebugLevel > 1 { return } l.Output(2, INFO+sprintf(f, o)) } func (l Logger) Debug(o ...interface{}) { if DebugLevel > 0 { return } l.Output(2, DEBUG+sprint(o)) } func (l Logger) Debugf(f string, o ...interface{}) { if DebugLevel > 0 { return } l.Output(2, DEBUG+sprintf(f, o)) } func (l Logger) Todo(o ...interface{}) { l.Output(2, TODO+sprint(o)) } func (l Logger) Error(o ...interface{}) { l.Output(2, ERROR+sprint(o)) } func (l Logger) Errorf(f string, o ...interface{}) { l.Output(2, ERROR+sprintf(f, o)) } func (l Logger) Warn(o ...interface{}) { l.Output(2, WARN+sprint(o)) } func (l Logger) Warnf(f string, o ...interface{}) { l.Output(2, WARN+sprintf(f, o)) } func (l Logger) Panic(o ...interface{}) { l.Output(2, PANIC+sprint(o)) panic(o) } func (l Logger) Panicf(f string, o ...interface{}) { info := sprintf(f, o) l.Output(2, PANIC+info) panic(info) } func (l Logger) Fatal(o ...interface{}) { l.Output(2, FATAL+sprint(o)) os.Exit(1) } func (l Logger) Fatalf(f string, o ...interface{}) { l.Output(2, FATAL+sprintf(f, o)) os.Exit(1) } func (l Logger) Struct(o ...interface{}) { items := make([]interface{}, 0, len(o)*2) for _, item := range o { items = append(items, item, item) } layout := strings.Repeat(", %T(%+v)", len(o)) if len(layout) > 0 { layout = layout[2:] } l.Output(2, STRUCT+sprintf(layout, items)) } func (l Logger) PrintStack() { Info(string(l.Stack())) } func (l Logger) Stack() []byte { a := make([]byte, 1024*1024) n := runtime.Stack(a, true) return a[:n] } func (l Logger) Output(calldepth int, s string) error { calldepth += l.depth + 1 if l.Logger == nil { l.Logger = goLogStd } return l.Logger.Output(calldepth, l.makePrefix(calldepth)+s) } func (l Logger) makePrefix(calldepth int) string { if !ShowCode { return "" } pc, f, line, _ := runtime.Caller(calldepth) name := runtime.FuncForPC(pc).Name() name = path.Base(name) // only use package.funcname f = path.Base(f) // only use filename tags := make([]string, 0, 3) pos := name + ":" + f + ":" + strconv.Itoa(line) tags = append(tags, pos) if l.reqid != "" { tags = append(tags, l.reqid) } return "[" + strings.Join(tags, "][") + "]" } func Sprint(o ...interface{}) string { return sprint(o) } func Sprintf(f string, o ...interface{}) string { return sprintf(f, o) } func sprint(o []interface{}) string { decodeTraceError(o) return joinInterface(o, " ") } func sprintf(f string, o []interface{}) string { decodeTraceError(o) return fmt.Sprintf(f, o...) } func DecodeError(e error) string { if e == nil { return "" } if e1, ok := e.(*traceError); ok { return e1.StackError() } return e.Error() } func decodeTraceError(o []interface{}) { if !ShowCode { return } for idx, obj := range o { if te, ok := obj.(*traceError); ok { o[idx] = te.StackError() } } } logex-1.2.1/logex_test.go000066400000000000000000000020001423124641700153310ustar00rootroot00000000000000package logex import ( "bytes" "io" "strings" "testing" ) func (s *S) hello() { s.Warn("warn in hello") } func log(buf io.Writer, s string) { Logger{Logger: NewGoLog(buf)}.Output(2, s) } func test(buf io.Writer) { log(buf, "aa") Info("b") NewLoggerEx(buf).Info("c") Error("ec") s.hello() Struct(&s, 1, "", false) } // ------------------------------------------------------------------- type S struct { Logger } var s = S{} func TestLogex(t *testing.T) { buf := bytes.NewBuffer(nil) logger := NewLoggerEx(buf) logger.depth = 1 goLogStd = logger.Logger SetStd(logger) test(buf) ret := buf.String() println("--------\n", ret) except := []string{ ".test:logex_test.go:19]aa", ".test:logex_test.go:20][INFO] b", ".test:logex_test.go:21][INFO] c", ".test:logex_test.go:22][ERROR] ec", ".(*S).hello:logex_test.go:11][WARN] warn in hello", } for _, e := range except { idx := strings.Index(ret, e) if idx < 0 { t.Fatal("except", e, "not found") } ret = ret[idx+len(e):] } }