From 789e4cf0209aa13cd1aff5302a679686e63fcf29 Mon Sep 17 00:00:00 2001 From: MuXiu1997 Date: Fri, 27 Jan 2023 14:50:41 +0800 Subject: [PATCH] feat(middleware): add log --- .traefik.yml | 1 + README.md | 3 + go.mod | 1 + go.sum | 2 + middleware_plugin.go | 32 ++ .../github.com/apsdehal/go-logger/.travis.yml | 2 + vendor/github.com/apsdehal/go-logger/LICENSE | 12 + .../github.com/apsdehal/go-logger/README.md | 146 ++++++ .../github.com/apsdehal/go-logger/logger.go | 471 ++++++++++++++++++ vendor/modules.txt | 3 + 10 files changed, 673 insertions(+) create mode 100644 vendor/github.com/apsdehal/go-logger/.travis.yml create mode 100644 vendor/github.com/apsdehal/go-logger/LICENSE create mode 100644 vendor/github.com/apsdehal/go-logger/README.md create mode 100644 vendor/github.com/apsdehal/go-logger/logger.go diff --git a/.traefik.yml b/.traefik.yml index 82371bd..8cca39d 100644 --- a/.traefik.yml +++ b/.traefik.yml @@ -14,6 +14,7 @@ testData: apiSecretKey: optional_secret_key_if_not_on_the_internal_network authPath: /_auth jwtSecretKey: optional_secret_key + logLevel: info whitelist: ids: - 996 diff --git a/README.md b/README.md index 6c5c640..ca6363b 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,9 @@ providing a more secure way for users to access protected routes. authPath: /_auth # optional jwt secret key, if not set, the plugin will generate a random key jwtSecretKey: optional_secret_key + # The log level, defaults to info + # Available values: debug, info, warn, error + logLevel: info # whitelist whitelist: # The list of GitHub user ids that in the whitelist diff --git a/go.mod b/go.mod index 87816ae..9a264a2 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/MuXiu1997/traefik-github-oauth-plugin go 1.19 require ( + github.com/apsdehal/go-logger v0.0.0-20190515212710-b0d6ccfee0e6 github.com/dghubble/sling v1.4.1 github.com/gin-gonic/gin v1.8.2 github.com/golang-jwt/jwt/v4 v4.4.3 diff --git a/go.sum b/go.sum index 693fa6a..65486d2 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/apsdehal/go-logger v0.0.0-20190515212710-b0d6ccfee0e6 h1:qISSdUEX4sjDHfdD/vf65fhuCh3pIhiILDB7ktjJrqU= +github.com/apsdehal/go-logger v0.0.0-20190515212710-b0d6ccfee0e6/go.mod h1:U3/8D6R9+bVpX0ORZjV+3mU9pQ86m7h1lESgJbXNvXA= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= diff --git a/middleware_plugin.go b/middleware_plugin.go index 53c5c28..fe608ff 100644 --- a/middleware_plugin.go +++ b/middleware_plugin.go @@ -6,11 +6,13 @@ import ( "encoding/hex" "fmt" "net/http" + "os" "strings" "github.com/MuXiu1997/traefik-github-oauth-plugin/internal/app/traefik-github-oauth-server/model" "github.com/MuXiu1997/traefik-github-oauth-plugin/internal/pkg/constant" "github.com/MuXiu1997/traefik-github-oauth-plugin/internal/pkg/jwt" + gologger "github.com/apsdehal/go-logger" "github.com/dghubble/sling" "github.com/scylladb/go-set/strset" ) @@ -25,6 +27,7 @@ type Config struct { ApiSecretKey string `json:"api_secret_key,omitempty"` AuthPath string `json:"auth_path,omitempty"` JwtSecretKey string `json:"jwt_secret_key,omitempty"` + LogLevel string `json:"log_level,omitempty"` Whitelist ConfigWhitelist `json:"whitelist,omitempty"` } @@ -62,16 +65,39 @@ type TraefikGithubOauthMiddleware struct { jwtSecretKey string whitelistIdSet *strset.Set whitelistLoginSet *strset.Set + + logger *gologger.Logger } var _ http.Handler = (*TraefikGithubOauthMiddleware)(nil) // New creates a new TraefikGithubOauthMiddleware. func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + // region Setup logger + logLevel := gologger.InfoLevel + switch config.LogLevel { + case "DEBUG", "debug": + logLevel = gologger.DebugLevel + case "INFO", "info": + logLevel = gologger.InfoLevel + case "WARNING", "warning", "WARN", "warn": + logLevel = gologger.WarningLevel + case "ERROR", "error": + logLevel = gologger.ErrorLevel + } + logger, err := gologger.New("TraefikGithubOauthMiddleware", os.Stdout, 0) + if err != nil { + return nil, err + } + logger.SetLogLevel(logLevel) + logger.SetFormat("[%{module}] | %{level} | %{time} | %{message}") + // endregion Setup logger + authPath := config.AuthPath if !strings.HasPrefix(authPath, "/") { authPath = "/" + authPath } + return &TraefikGithubOauthMiddleware{ ctx: ctx, next: next, @@ -83,6 +109,8 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h jwtSecretKey: config.JwtSecretKey, whitelistIdSet: strset.New(config.Whitelist.Ids...), whitelistLoginSet: strset.New(config.Whitelist.Logins...), + + logger: logger, }, nil } @@ -99,6 +127,7 @@ func (p *TraefikGithubOauthMiddleware) ServeHTTP(rw http.ResponseWriter, req *ht func (p *TraefikGithubOauthMiddleware) handleRequest(rw http.ResponseWriter, req *http.Request) { user, err := p.getGitHubUserFromCookie(req) if err != nil { + p.logger.Debugf("handleRequest: getGitHubUserFromCookie: %s\n", err.Error()) if req.Method == http.MethodGet { p.redirectToOAuthPage(rw, req) } @@ -117,11 +146,13 @@ func (p *TraefikGithubOauthMiddleware) handleAuthRequest(rw http.ResponseWriter, rid := req.URL.Query().Get(constant.QUERY_KEY_REQUEST_ID) result, err := p.getAuthResult(rid) if err != nil { + p.logger.Debugf("handleAuthRequest: getAuthResult: %s\n", err.Error()) http.Error(rw, err.Error(), http.StatusInternalServerError) return } tokenString, err := jwt.GenerateJwtTokenString(result.GitHubUserID, result.GitHubUserLogin, p.jwtSecretKey) if err != nil { + p.logger.Debugf("handleAuthRequest: GenerateJwtTokenString: %s\n", err.Error()) http.Error(rw, err.Error(), http.StatusInternalServerError) return } @@ -136,6 +167,7 @@ func (p *TraefikGithubOauthMiddleware) handleAuthRequest(rw http.ResponseWriter, func (p *TraefikGithubOauthMiddleware) redirectToOAuthPage(rw http.ResponseWriter, req *http.Request) { oAuthPageURL, err := p.generateOAuthPageURL(getRawRequestUrl(req), p.getAuthURL(req)) if err != nil { + p.logger.Debugf("redirectToOAuthPage: generateOAuthPageURL: %s\n", err.Error()) http.Error(rw, err.Error(), http.StatusInternalServerError) return } diff --git a/vendor/github.com/apsdehal/go-logger/.travis.yml b/vendor/github.com/apsdehal/go-logger/.travis.yml new file mode 100644 index 0000000..fb9efcb --- /dev/null +++ b/vendor/github.com/apsdehal/go-logger/.travis.yml @@ -0,0 +1,2 @@ +language: go +go: 1.2 diff --git a/vendor/github.com/apsdehal/go-logger/LICENSE b/vendor/github.com/apsdehal/go-logger/LICENSE new file mode 100644 index 0000000..1b554b5 --- /dev/null +++ b/vendor/github.com/apsdehal/go-logger/LICENSE @@ -0,0 +1,12 @@ +Copyright (c) 2014, Amanpreet Singh +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/vendor/github.com/apsdehal/go-logger/README.md b/vendor/github.com/apsdehal/go-logger/README.md new file mode 100644 index 0000000..52b7d30 --- /dev/null +++ b/vendor/github.com/apsdehal/go-logger/README.md @@ -0,0 +1,146 @@ + +# go-logger + +[![Build Status](https://travis-ci.org/apsdehal/go-logger.svg?branch=master)](https://travis-ci.org/apsdehal/go-logger) +[![GoDoc](https://godoc.org/github.com/apsdehal/go-logger?status.svg)](http://godoc.org/github.com/apsdehal/go-logger) + +A simple go logger for easy logging in your programs. Allows setting custom format for messages. + +# Preview + +[![Example Output](examples/example.png)](examples/example.go) + + +# Install + +`go get github.com/apsdehal/go-logger` + +Use `go get -u` to update the package. + +# Example + +Example [program](examples/example.go) demonstrates how to use the logger. See below for __formatting__ instructions. + + +```go +package main + +import ( + "github.com/apsdehal/go-logger" + "os" +) + +func main () { + // Get the instance for logger class, "test" is the module name, 1 is used to + // state if we want coloring + // Third option is optional and is instance of type io.Writer, defaults to os.Stderr + log, err := logger.New("test", 1, os.Stdout) + if err != nil { + panic(err) // Check for error + } + + // Critically log critical + log.Critical("This is Critical!") + log.CriticalF("%+v", err) + // You can also use fmt compliant naming scheme such as log.Criticalf, log.Panicf etc + // with small 'f' + + // Debug + // Since default logging level is Info this won't print anything + log.Debug("This is Debug!") + log.DebugF("Here are some numbers: %d %d %f", 10, -3, 3.14) + // Give the Warning + log.Warning("This is Warning!") + log.WarningF("This is Warning!") + // Show the error + log.Error("This is Error!") + log.ErrorF("This is Error!") + // Notice + log.Notice("This is Notice!") + log.NoticeF("%s %s", "This", "is Notice!") + // Show the info + log.Info("This is Info!") + log.InfoF("This is %s!", "Info") + + log.StackAsError("Message before printing stack"); + + // Show warning with format + log.SetFormat("[%{module}] [%{level}] %{message}") + log.Warning("This is Warning!") // output: "[test] [WARNING] This is Warning!" + // Also you can set your format as default format for all new loggers + logger.SetDefaultFormat("%{message}") + log2, _ := logger.New("pkg", 1, os.Stdout) + log2.Error("This is Error!") // output: "This is Error!" + + // Use log levels to set your log priority + log2.SetLogLevel(DebugLevel) + // This will be printed + log2.Debug("This is debug!") + log2.SetLogLevel(WarningLevel) + // This won't be printed + log2.Info("This is an error!") +} +``` + + +# Formatting + +By default all log messages have format that you can see above (on pic). +But you can override the default format and set format that you want. + +You can do it for Logger instance (after creating logger) ... +```go +log, _ := logger.New("pkgname", 1) +log.SetFormat(format) +``` +... or for package +```go +logger.SetDefaultFormat(format) +``` +If you do it for package, all existing loggers will print log messages with format that these used already. +But all newest loggers (which will be created after changing format for package) will use your specified format. + +But anyway after this, you can still set format of message for specific Logger instance. + +Format of log message must contains verbs that represent some info about current log entry. +Ofc, format can contain not only verbs but also something else (for example text, digits, symbols, etc) + +### Format verbs: +You can use the following verbs: +``` +%{id} - means number of current log message +%{module} - means module name (that you passed to func New()) +%{time} - means current time in format "2006-01-02 15:04:05" +%{time:format} - means current time in format that you want + (supports all formats supported by go package "time") +%{level} - means level name (upper case) of log message ("ERROR", "DEBUG", etc) +%{lvl} - means first 3 letters of level name (upper case) of log message ("ERR", "DEB", etc) +%{file} - means name of file in what you wanna write log +%{filename} - means the same as %{file} +%{line} - means line number of file in what you wanna write log +%{message} - means your log message +``` +Non-existent verbs (like ```%{nonex-verb}``` or ```%{}```) will be replaced by an empty string. +Invalid verbs (like ```%{inv-verb```) will be treated as plain text. + +# Tests + +Run: +- `go test logger` to run test on logger. +- `go test -bench=.` for benchmarks. + +## Thanks + +Thanks goes to all go-loggers out there which I used as reference. + +## Contributors + +Following contributors have made major contributions to go-logger: + +- [@qioalice](https://github.com/qioalice) +- [@gjvnq](https://github.com/gjvnq) +- [@maezen](https://github.com/maezen) + +## License + +The [BSD 3-Clause license](http://opensource.org/licenses/BSD-3-Clause), the same as the [Go language](http://golang.org/LICENSE). diff --git a/vendor/github.com/apsdehal/go-logger/logger.go b/vendor/github.com/apsdehal/go-logger/logger.go new file mode 100644 index 0000000..3c83cd5 --- /dev/null +++ b/vendor/github.com/apsdehal/go-logger/logger.go @@ -0,0 +1,471 @@ +// Package name declaration +package logger + +// Import packages +import ( + "bytes" + "fmt" + "io" + "log" + "os" + "path" + "runtime" + "strings" + "sync/atomic" + "time" +) + +var ( + // Map for the various codes of colors + colors map[LogLevel]string + + // Map from format's placeholders to printf verbs + phfs map[string]string + + // Contains color strings for stdout + logNo uint64 + + // Default format of log message + defFmt = "#%[1]d %[2]s %[4]s:%[5]d ▶ %.3[6]s %[7]s" + + // Default format of time + defTimeFmt = "2006-01-02 15:04:05" +) + +// LogLevel type +type LogLevel int + +// Color numbers for stdout +const ( + Black = (iota + 30) + Red + Green + Yellow + Blue + Magenta + Cyan + White +) + +// Log Level +const ( + CriticalLevel LogLevel = iota + 1 + ErrorLevel + WarningLevel + NoticeLevel + InfoLevel + DebugLevel +) + +// Worker class, Worker is a log object used to log messages and Color specifies +// if colored output is to be produced +type Worker struct { + Minion *log.Logger + Color int + format string + timeFormat string + level LogLevel +} + +// Info class, Contains all the info on what has to logged, time is the current time, Module is the specific module +// For which we are logging, level is the state, importance and type of message logged, +// Message contains the string to be logged, format is the format of string to be passed to sprintf +type Info struct { + Id uint64 + Time string + Module string + Level LogLevel + Line int + Filename string + Message string + //format string +} + +// Logger class that is an interface to user to log messages, Module is the module for which we are testing +// worker is variable of Worker class that is used in bottom layers to log the message +type Logger struct { + Module string + worker *Worker +} + +// init pkg +func init() { + initColors() + initFormatPlaceholders() +} + +// Returns a proper string to be outputted for a particular info +func (r *Info) Output(format string) string { + msg := fmt.Sprintf(format, + r.Id, // %[1] // %{id} + r.Time, // %[2] // %{time[:fmt]} + r.Module, // %[3] // %{module} + r.Filename, // %[4] // %{filename} + r.Line, // %[5] // %{line} + r.logLevelString(), // %[6] // %{level} + r.Message, // %[7] // %{message} + ) + // Ignore printf errors if len(args) > len(verbs) + if i := strings.LastIndex(msg, "%!(EXTRA"); i != -1 { + return msg[:i] + } + return msg +} + +// Analyze and represent format string as printf format string and time format +func parseFormat(format string) (msgfmt, timefmt string) { + if len(format) < 10 /* (len of "%{message} */ { + return defFmt, defTimeFmt + } + timefmt = defTimeFmt + idx := strings.IndexRune(format, '%') + for idx != -1 { + msgfmt += format[:idx] + format = format[idx:] + if len(format) > 2 { + if format[1] == '{' { + // end of curr verb pos + if jdx := strings.IndexRune(format, '}'); jdx != -1 { + // next verb pos + idx = strings.Index(format[1:], "%{") + // incorrect verb found ("...%{wefwef ...") but after + // this, new verb (maybe) exists ("...%{inv %{verb}...") + if idx != -1 && idx < jdx { + msgfmt += "%%" + format = format[1:] + continue + } + // get verb and arg + verb, arg := ph2verb(format[:jdx+1]) + msgfmt += verb + // check if verb is time + // here you can handle args for other verbs + if verb == `%[2]s` && arg != "" /* %{time} */ { + timefmt = arg + } + format = format[jdx+1:] + } else { + format = format[1:] + } + } else { + msgfmt += "%%" + format = format[1:] + } + } + idx = strings.IndexRune(format, '%') + } + msgfmt += format + return +} + +// translate format placeholder to printf verb and some argument of placeholder +// (now used only as time format) +func ph2verb(ph string) (verb string, arg string) { + n := len(ph) + if n < 4 { + return ``, `` + } + if ph[0] != '%' || ph[1] != '{' || ph[n-1] != '}' { + return ``, `` + } + idx := strings.IndexRune(ph, ':') + if idx == -1 { + return phfs[ph], `` + } + verb = phfs[ph[:idx]+"}"] + arg = ph[idx+1 : n-1] + return +} + +// Returns an instance of worker class, prefix is the string attached to every log, +// flag determine the log params, color parameters verifies whether we need colored outputs or not +func NewWorker(prefix string, flag int, color int, out io.Writer) *Worker { + return &Worker{Minion: log.New(out, prefix, flag), Color: color, format: defFmt, timeFormat: defTimeFmt} +} + +func SetDefaultFormat(format string) { + defFmt, defTimeFmt = parseFormat(format) +} + +func (w *Worker) SetFormat(format string) { + w.format, w.timeFormat = parseFormat(format) +} + +func (l *Logger) SetFormat(format string) { + l.worker.SetFormat(format) +} + +func (w *Worker) SetLogLevel(level LogLevel) { + w.level = level +} + +func (l *Logger) SetLogLevel(level LogLevel) { + l.worker.level = level +} + +// Function of Worker class to log a string based on level +func (w *Worker) Log(level LogLevel, calldepth int, info *Info) error { + + if w.level < level { + return nil + } + + if w.Color != 0 { + buf := &bytes.Buffer{} + buf.Write([]byte(colors[level])) + buf.Write([]byte(info.Output(w.format))) + buf.Write([]byte("\033[0m")) + return w.Minion.Output(calldepth+1, buf.String()) + } else { + return w.Minion.Output(calldepth+1, info.Output(w.format)) + } +} + +// Returns a proper string to output for colored logging +func colorString(color int) string { + return fmt.Sprintf("\033[%dm", int(color)) +} + +// Initializes the map of colors +func initColors() { + colors = map[LogLevel]string{ + CriticalLevel: colorString(Magenta), + ErrorLevel: colorString(Red), + WarningLevel: colorString(Yellow), + NoticeLevel: colorString(Green), + DebugLevel: colorString(Cyan), + InfoLevel: colorString(White), + } +} + +// Initializes the map of placeholders +func initFormatPlaceholders() { + phfs = map[string]string{ + "%{id}": "%[1]d", + "%{time}": "%[2]s", + "%{module}": "%[3]s", + "%{filename}": "%[4]s", + "%{file}": "%[4]s", + "%{line}": "%[5]d", + "%{level}": "%[6]s", + "%{lvl}": "%.3[6]s", + "%{message}": "%[7]s", + } +} + +// Returns a new instance of logger class, module is the specific module for which we are logging +// , color defines whether the output is to be colored or not, out is instance of type io.Writer defaults +// to os.Stderr +func New(args ...interface{}) (*Logger, error) { + //initColors() + + var module string = "DEFAULT" + var color int = 1 + var out io.Writer = os.Stderr + var level LogLevel = InfoLevel + + for _, arg := range args { + switch t := arg.(type) { + case string: + module = t + case int: + color = t + case io.Writer: + out = t + case LogLevel: + level = t + default: + panic("logger: Unknown argument") + } + } + newWorker := NewWorker("", 0, color, out) + newWorker.SetLogLevel(level) + return &Logger{Module: module, worker: newWorker}, nil +} + +// The log commnand is the function available to user to log message, lvl specifies +// the degree of the messagethe user wants to log, message is the info user wants to log +func (l *Logger) Log(lvl LogLevel, message string) { + l.log_internal(lvl, message, 2) +} + +func (l *Logger) log_internal(lvl LogLevel, message string, pos int) { + //var formatString string = "#%d %s [%s] %s:%d ▶ %.3s %s" + _, filename, line, _ := runtime.Caller(pos) + filename = path.Base(filename) + info := &Info{ + Id: atomic.AddUint64(&logNo, 1), + Time: time.Now().Format(l.worker.timeFormat), + Module: l.Module, + Level: lvl, + Message: message, + Filename: filename, + Line: line, + //format: formatString, + } + l.worker.Log(lvl, 2, info) +} + +// Fatal is just like func l.Critical logger except that it is followed by exit to program +func (l *Logger) Fatal(message string) { + l.log_internal(CriticalLevel, message, 2) + os.Exit(1) +} + +// FatalF is just like func l.CriticalF logger except that it is followed by exit to program +func (l *Logger) FatalF(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) + os.Exit(1) +} + +// FatalF is just like func l.CriticalF logger except that it is followed by exit to program +func (l *Logger) Fatalf(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) + os.Exit(1) +} + +// Panic is just like func l.Critical except that it is followed by a call to panic +func (l *Logger) Panic(message string) { + l.log_internal(CriticalLevel, message, 2) + panic(message) +} + +// PanicF is just like func l.CriticalF except that it is followed by a call to panic +func (l *Logger) PanicF(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) + panic(fmt.Sprintf(format, a...)) +} + +// PanicF is just like func l.CriticalF except that it is followed by a call to panic +func (l *Logger) Panicf(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) + panic(fmt.Sprintf(format, a...)) +} + +// Critical logs a message at a Critical Level +func (l *Logger) Critical(message string) { + l.log_internal(CriticalLevel, message, 2) +} + +// CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf +func (l *Logger) CriticalF(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) +} + +// CriticalF logs a message at Critical level using the same syntax and options as fmt.Printf +func (l *Logger) Criticalf(format string, a ...interface{}) { + l.log_internal(CriticalLevel, fmt.Sprintf(format, a...), 2) +} + +// Error logs a message at Error level +func (l *Logger) Error(message string) { + l.log_internal(ErrorLevel, message, 2) +} + +// ErrorF logs a message at Error level using the same syntax and options as fmt.Printf +func (l *Logger) ErrorF(format string, a ...interface{}) { + l.log_internal(ErrorLevel, fmt.Sprintf(format, a...), 2) +} + +// ErrorF logs a message at Error level using the same syntax and options as fmt.Printf +func (l *Logger) Errorf(format string, a ...interface{}) { + l.log_internal(ErrorLevel, fmt.Sprintf(format, a...), 2) +} + +// Warning logs a message at Warning level +func (l *Logger) Warning(message string) { + l.log_internal(WarningLevel, message, 2) +} + +// WarningF logs a message at Warning level using the same syntax and options as fmt.Printf +func (l *Logger) WarningF(format string, a ...interface{}) { + l.log_internal(WarningLevel, fmt.Sprintf(format, a...), 2) +} + +// WarningF logs a message at Warning level using the same syntax and options as fmt.Printf +func (l *Logger) Warningf(format string, a ...interface{}) { + l.log_internal(WarningLevel, fmt.Sprintf(format, a...), 2) +} + +// Notice logs a message at Notice level +func (l *Logger) Notice(message string) { + l.log_internal(NoticeLevel, message, 2) +} + +// NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf +func (l *Logger) NoticeF(format string, a ...interface{}) { + l.log_internal(NoticeLevel, fmt.Sprintf(format, a...), 2) +} + +// NoticeF logs a message at Notice level using the same syntax and options as fmt.Printf +func (l *Logger) Noticef(format string, a ...interface{}) { + l.log_internal(NoticeLevel, fmt.Sprintf(format, a...), 2) +} + +// Info logs a message at Info level +func (l *Logger) Info(message string) { + l.log_internal(InfoLevel, message, 2) +} + +// InfoF logs a message at Info level using the same syntax and options as fmt.Printf +func (l *Logger) InfoF(format string, a ...interface{}) { + l.log_internal(InfoLevel, fmt.Sprintf(format, a...), 2) +} + +// InfoF logs a message at Info level using the same syntax and options as fmt.Printf +func (l *Logger) Infof(format string, a ...interface{}) { + l.log_internal(InfoLevel, fmt.Sprintf(format, a...), 2) +} + +// Debug logs a message at Debug level +func (l *Logger) Debug(message string) { + l.log_internal(DebugLevel, message, 2) +} + +// DebugF logs a message at Debug level using the same syntax and options as fmt.Printf +func (l *Logger) DebugF(format string, a ...interface{}) { + l.log_internal(DebugLevel, fmt.Sprintf(format, a...), 2) +} + +// DebugF logs a message at Debug level using the same syntax and options as fmt.Printf +func (l *Logger) Debugf(format string, a ...interface{}) { + l.log_internal(DebugLevel, fmt.Sprintf(format, a...), 2) +} + +// Prints this goroutine's execution stack as an error with an optional message at the begining +func (l *Logger) StackAsError(message string) { + if message == "" { + message = "Stack info" + } + message += "\n" + l.log_internal(ErrorLevel, message+Stack(), 2) +} + +// Prints this goroutine's execution stack as critical with an optional message at the begining +func (l *Logger) StackAsCritical(message string) { + if message == "" { + message = "Stack info" + } + message += "\n" + l.log_internal(CriticalLevel, message+Stack(), 2) +} + +// Returns a string with the execution stack for this goroutine +func Stack() string { + buf := make([]byte, 1000000) + runtime.Stack(buf, false) + return string(buf) +} + +// Returns the loglevel as string +func (info *Info) logLevelString() string { + logLevels := [...]string{ + "CRITICAL", + "ERROR", + "WARNING", + "NOTICE", + "INFO", + "DEBUG", + } + return logLevels[info.Level-1] +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7ff074f..1d489c8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,6 @@ +# github.com/apsdehal/go-logger v0.0.0-20190515212710-b0d6ccfee0e6 +## explicit +github.com/apsdehal/go-logger # github.com/davecgh/go-spew v1.1.1 ## explicit github.com/davecgh/go-spew/spew