Fix linter

This commit is contained in:
Nicolas JUHEL
2020-08-17 10:47:25 +02:00
parent 32ad79d92a
commit c9b6a9d1ee
14 changed files with 158 additions and 89 deletions

View File

@@ -40,31 +40,41 @@ var (
defaultPatternTrace = "[Error #%s] %s (%s)" defaultPatternTrace = "[Error #%s] %s (%s)"
) )
// SetTracePathFilter define the glue string to be used to join main error with parents'errors.
func SetDefaultGlue(glue string) { func SetDefaultGlue(glue string) {
defaultGlue = glue defaultGlue = glue
} }
// GetDefaultGlue return the current glue used to joins errors with parents.
func GetDefaultGlue() string { func GetDefaultGlue() string {
return defaultGlue return defaultGlue
} }
// GetDefaultPatternTrace define the pattern to be used for string of error with code.
// The pattern is fmt pattern with 2 inputs in order : code, message.
func SetDefaultPattern(pattern string) { func SetDefaultPattern(pattern string) {
defaultPattern = pattern defaultPattern = pattern
} }
// GetDefaultPattern return the current pattern used for string of error with code.
// The pattern is fmt pattern with 2 inputs in order : code, message.
func GetDefaultPattern() string { func GetDefaultPattern() string {
return defaultPattern return defaultPattern
} }
// SetDefaultPatternTrace define the pattern to be used for string of error with code and trace.
// The pattern is fmt pattern with 3 inputs in order : code, message, trace.
func SetDefaultPatternTrace(patternTrace string) { func SetDefaultPatternTrace(patternTrace string) {
defaultPatternTrace = patternTrace defaultPatternTrace = patternTrace
} }
// GetDefaultPatternTrace return the current pattern used for string of error with code and trace.
// The pattern is fmt pattern with 3 inputs in order : code, message, trace.
func GetDefaultPatternTrace() string { func GetDefaultPatternTrace() string {
return defaultPatternTrace return defaultPatternTrace
} }
// SetTracePathFilter customize the filter apply to filepath on trace // SetTracePathFilter customize the filter apply to filepath on trace.
func SetTracePathFilter(path string) { func SetTracePathFilter(path string) {
filterPkg = path filterPkg = path
} }
@@ -295,10 +305,12 @@ func (e *errors) StringErrorSlice() []string {
} }
func (e *errors) GetError() error { func (e *errors) GetError() error {
//nolint goerr113
return errs.New(e.e) return errs.New(e.e)
} }
func (e *errors) GetErrorFull(glue string) error { func (e *errors) GetErrorFull(glue string) error {
//nolint goerr113
return errs.New(e.StringErrorFull(glue)) return errs.New(e.StringErrorFull(glue))
} }

View File

@@ -51,7 +51,10 @@ const (
) )
func (m ErrorMode) String() string { func (m ErrorMode) String() string {
//nolint exhaustive
switch m { switch m {
case Default:
return "default"
case ErrorReturnCode: case ErrorReturnCode:
return "Code" return "Code"
case ErrorReturnCodeFull: case ErrorReturnCodeFull:
@@ -68,15 +71,16 @@ func (m ErrorMode) String() string {
return "StringError" return "StringError"
case ErrorReturnStringErrorFull: case ErrorReturnStringErrorFull:
return "StringErrorFull" return "StringErrorFull"
case Default:
return "default"
} }
return Default.String() return Default.String()
} }
func (m ErrorMode) error(e *errors) string { func (m ErrorMode) error(e *errors) string {
//nolint exhaustive
switch m { switch m {
case Default:
return e.StringError()
case ErrorReturnCode: case ErrorReturnCode:
return e.Code() return e.Code()
case ErrorReturnCodeFull: case ErrorReturnCodeFull:
@@ -93,8 +97,6 @@ func (m ErrorMode) error(e *errors) string {
return e.StringError() return e.StringError()
case ErrorReturnStringErrorFull: case ErrorReturnStringErrorFull:
return e.StringErrorFull("") return e.StringErrorFull("")
case Default:
return e.StringError()
} }
return Default.error(e) return Default.error(e)

View File

@@ -32,11 +32,9 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/nabbar/golib/certificates"
"github.com/nabbar/golib/errors"
"golang.org/x/net/http2" "golang.org/x/net/http2"
. "github.com/nabbar/golib/errors"
certif "github.com/nabbar/golib/certificates"
) )
const ( const (
@@ -47,24 +45,24 @@ const (
) )
func GetClient(serverName string) *http.Client { func GetClient(serverName string) *http.Client {
c, e := getClient(true, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certif.GetTLSConfig(serverName)) c, e := getClient(true, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certificates.GetTLSConfig(serverName))
if e != nil { if e != nil {
c, _ = getClient(false, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certif.GetTLSConfig(serverName)) c, _ = getClient(false, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certificates.GetTLSConfig(serverName))
} }
return c return c
} }
func GetClientError(serverName string) (*http.Client, Error) { func GetClientError(serverName string) (*http.Client, errors.Error) {
return getClient(true, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certif.GetTLSConfig(serverName)) return getClient(true, TIMEOUT_30_SEC, TIMEOUT_10_SEC, TIMEOUT_30_SEC, TIMEOUT_30_SEC, TIMEOUT_5_SEC, TIMEOUT_1_SEC, certificates.GetTLSConfig(serverName))
} }
func GetClientTimeout(serverName string, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout time.Duration) (*http.Client, Error) { func GetClientTimeout(serverName string, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout time.Duration) (*http.Client, errors.Error) {
return getClient(true, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout, certif.GetTLSConfig(serverName)) return getClient(true, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout, certificates.GetTLSConfig(serverName))
} }
func getClient(http2Transport bool, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout time.Duration, tlsConfig *tls.Config) (*http.Client, Error) { func getClient(http2Transport bool, GlobalTimeout, DialTimeOut, DialKeepAlive, IdleConnTimeout, TLSHandshakeTimeout, ExpectContinueTimeout time.Duration, tlsConfig *tls.Config) (*http.Client, errors.Error) {
tr := &http.Transport{ tr := &http.Transport{
Proxy: http.ProxyFromEnvironment, Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{ DialContext: (&net.Dialer{

View File

@@ -52,6 +52,8 @@ func init() {
func getMessage(code errors.CodeError) (message string) { func getMessage(code errors.CodeError) (message string) {
switch code { switch code {
case errors.UNK_ERROR:
return ""
case EMPTY_PARAMS: case EMPTY_PARAMS:
return "given parameters is empty" return "given parameters is empty"
case URL_PARSE: case URL_PARSE:

View File

@@ -27,6 +27,7 @@ package httpcli
import ( import (
"bytes" "bytes"
"context"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
@@ -39,9 +40,11 @@ import (
type httpClient struct { type httpClient struct {
url *url.URL url *url.URL
cli *http.Client cli *http.Client
ctx context.Context
} }
type HTTP interface { type HTTP interface {
SetContext(ctx context.Context)
Check() errors.Error Check() errors.Error
Call(file *bytes.Buffer) (bool, *bytes.Buffer, errors.Error) Call(file *bytes.Buffer) (bool, *bytes.Buffer, errors.Error)
} }
@@ -75,9 +78,16 @@ func NewClient(uri string) (HTTP, errors.Error) {
return &httpClient{ return &httpClient{
url: pUri, url: pUri,
cli: c, cli: c,
ctx: context.Background(),
}, nil }, nil
} }
func (obj *httpClient) SetContext(ctx context.Context) {
if ctx != nil {
obj.ctx = ctx
}
}
func (obj *httpClient) Check() errors.Error { func (obj *httpClient) Check() errors.Error {
req, e := obj.newRequest(http.MethodHead, nil) req, e := obj.newRequest(http.MethodHead, nil)
@@ -119,7 +129,7 @@ func (obj *httpClient) newRequest(method string, body *bytes.Buffer) (*http.Requ
reader = bytes.NewReader(body.Bytes()) reader = bytes.NewReader(body.Bytes())
} }
req, e := http.NewRequest(method, obj.url.String(), reader) req, e := http.NewRequestWithContext(obj.ctx, method, obj.url.String(), reader)
if e != nil { if e != nil {
return req, HTTP_REQUEST.ErrorParent(e) return req, HTTP_REQUEST.ErrorParent(e)
} }

View File

@@ -31,32 +31,37 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
// Format a uint8 type customized with function to manage the result logger format // Format a uint8 type customized with function to manage the result logger format.
type Format uint8 type Format uint8
const ( const (
nilFormat Format = iota nilFormat Format = iota
// TextFormat a text format for logger entry // TextFormat a text format for logger entry.
TextFormat TextFormat
// JsonFormat a json format for logger entry // JsonFormat a json format for logger entry.
JsonFormat JsonFormat
) )
var ( var (
curFormat = TextFormat curFormat = nilFormat
) )
func init() {
updateFormatter(TextFormat)
}
func SetOutput(out io.WriteCloser) { func SetOutput(out io.WriteCloser) {
logrus.SetOutput(out) logrus.SetOutput(out)
} }
func updateFormatter(newFormat Format) { func updateFormatter(newFormat Format) {
if newFormat != nilFormat { switch newFormat {
curFormat = newFormat
} case curFormat:
return
switch curFormat {
case TextFormat: case TextFormat:
curFormat = TextFormat
logrus.SetFormatter(&logrus.TextFormatter{ logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: modeColor, ForceColors: modeColor,
DisableColors: !modeColor, DisableColors: !modeColor,
@@ -64,14 +69,20 @@ func updateFormatter(newFormat Format) {
DisableTimestamp: true, DisableTimestamp: true,
DisableSorting: true, DisableSorting: true,
}) })
case JsonFormat: case JsonFormat:
curFormat = JsonFormat
logrus.SetFormatter(&logrus.JSONFormatter{ logrus.SetFormatter(&logrus.JSONFormatter{
DisableTimestamp: true, DisableTimestamp: true,
}) })
case nilFormat:
return
} }
} }
// GetFormatListString return the full list (slice of string) of all available formats // GetFormatListString return the full list (slice of string) of all available formats.
func GetFormatListString() []string { func GetFormatListString() []string {
return []string{ return []string{
strings.ToLower(TextFormat.String()), strings.ToLower(TextFormat.String()),
@@ -79,8 +90,7 @@ func GetFormatListString() []string {
} }
} }
// SetFormat Change the format of all log entry with the Format type given in parameter. The change is apply for next entry only // SetFormat Change the format of all log entry with the Format type given in parameter. The change is apply for next entry only.
//
// If the given Format type is not matching a correct Format type, no change will be apply. // If the given Format type is not matching a correct Format type, no change will be apply.
/* /*
fmt a Format type for the format to use fmt a Format type for the format to use
@@ -89,15 +99,17 @@ func SetFormat(fmt Format) {
switch fmt { switch fmt {
case TextFormat, JsonFormat: case TextFormat, JsonFormat:
updateFormatter(fmt) updateFormatter(fmt)
case curFormat, nilFormat:
return
} }
} }
// GetCurrentFormat Return the current Format Type used for all log entry // GetCurrentFormat Return the current Format Type used for all log entry.
func GetCurrentFormat() Format { func GetCurrentFormat() Format {
return curFormat return curFormat
} }
// GetFormatString return a valid Format Type matching the given string parameter // GetFormatString return a valid Format Type matching the given string parameter.
/* /*
format the string representation of a Format type format the string representation of a Format type
*/ */
@@ -108,18 +120,21 @@ func GetFormatString(format string) Format {
case strings.ToLower(JsonFormat.String()): case strings.ToLower(JsonFormat.String()):
return JsonFormat return JsonFormat
default:
return TextFormat
} }
return GetFormatString(TextFormat.String())
} }
// String Return the string name of the Format Type // String Return the string name of the Format Type.
func (f Format) String() string { func (f Format) String() string {
switch f { switch f {
case JsonFormat: case JsonFormat:
return "Json" return "Json"
default: case TextFormat:
return "Text" return "Text"
case nilFormat, curFormat:
return ""
} }
return TextFormat.String()
} }

View File

@@ -29,13 +29,13 @@ import (
"io" "io"
) )
// IOWriter is struct redirected all entry to the current logger // IOWriter is struct redirected all entry to the current logger.
type IOWriter struct { type IOWriter struct {
lvl Level lvl Level
prf string prf string
} }
// GetIOWriter return a io.Writer instance to Write on logger with a specified log level // GetIOWriter return a io.Writer instance to Write on logger with a specified log level.
/* /*
level specify the log level to use to redirect all entry to current logger level specify the log level to use to redirect all entry to current logger
msgPrefixPattern is a string pattern to prefix all entry msgPrefixPattern is a string pattern to prefix all entry
@@ -48,9 +48,8 @@ func GetIOWriter(level Level, msgPrefixPattern string, msgPrefixArgs ...interfac
} }
} }
// Write implement the Write function of the io.Writer interface and redirect all entry to current logger // Write implement the Write function of the io.Writer interface and redirect all entry to current logger.
// // The return n will always return the len on the p parameter and err will always be nil.
// the return n will always return the len on the p parameter and err will always be nil
/* /*
p the entry to be redirect to current logger p the entry to be redirect to current logger
*/ */

View File

@@ -35,36 +35,40 @@ import (
"github.com/spf13/jwalterweatherman" "github.com/spf13/jwalterweatherman"
) )
//Level a uint8 type customized with function to log message with the current log level //Level a uint8 type customized with function to log message with the current log level.
type Level uint8 type Level uint8
const ( const (
// PanicLevel Panic level for entry log, will result on a Panic() call (trace + fatal) // PanicLevel Panic level for entry log, will result on a Panic() call (trace + fatal).
PanicLevel Level = iota PanicLevel Level = iota
// FatalLevel Fatal level for entry log, will result on os.Exit with error // FatalLevel Fatal level for entry log, will result on os.Exit with error.
FatalLevel FatalLevel
// ErrorLevel Error level for entry log who's meaning the caller stop his process and return to the pre caller // ErrorLevel Error level for entry log who's meaning the caller stop his process and return to the pre caller.
ErrorLevel ErrorLevel
// WarnLevel Warning level for entry log who's meaning the caller don't stop his process and try to continue it // WarnLevel Warning level for entry log who's meaning the caller don't stop his process and try to continue it.
WarnLevel WarnLevel
// InfoLevel Info level for entry log who's meaning it is just an information who's have no impact on caller's process but can be useful to inform human of a state, event, success, ... // InfoLevel Info level for entry log who's meaning it is just an information who's have no impact on caller's process but can be useful to inform human of a state, event, success, ...
InfoLevel InfoLevel
// DebugLevel Debug level for entry log who's meaning the caller has no problem and the information is only useful to identify a potential problem who's can arrive later // DebugLevel Debug level for entry log who's meaning the caller has no problem and the information is only useful to identify a potential problem who's can arrive later.
DebugLevel DebugLevel
// NilLevel Nil level will never log anything and is used to completely disable current log entry. It cannot be used in the SetLogLevel function // NilLevel Nil level will never log anything and is used to completely disable current log entry. It cannot be used in the SetLogLevel function.
NilLevel NilLevel
) )
var ( var (
curLevel = InfoLevel curLevel = NilLevel
) )
//GetCurrentLevel return the current loglevel setting in the logger. All log entry matching this level or below will be logged func init() {
SetLevel(InfoLevel)
}
//GetCurrentLevel return the current loglevel setting in the logger. All log entry matching this level or below will be logged.
func GetCurrentLevel() Level { func GetCurrentLevel() Level {
return curLevel return curLevel
} }
// GetLevelListString return a list ([]string) of all string loglevel available // GetLevelListString return a list ([]string) of all string loglevel available.
func GetLevelListString() []string { func GetLevelListString() []string {
return []string{ return []string{
strings.ToLower(PanicLevel.String()), strings.ToLower(PanicLevel.String()),
@@ -76,14 +80,15 @@ func GetLevelListString() []string {
} }
} }
// SetLevel Change the Level of all log entry with the Level type given in parameter. The change is apply for next log entry only // SetLevel Change the Level of all log entry with the Level type given in parameter. The change is apply for next log entry only.
//
// If the given Level type is not matching a correct Level type, no change will be apply. // If the given Level type is not matching a correct Level type, no change will be apply.
/* /*
level a Level type to use to specify the new level of logger message level a Level type to use to specify the new level of logger message
*/ */
func SetLevel(level Level) { func SetLevel(level Level) {
//nolint exhaustive
switch level { switch level {
case PanicLevel: case PanicLevel:
curLevel = PanicLevel curLevel = PanicLevel
logrus.SetLevel(logrus.PanicLevel) logrus.SetLevel(logrus.PanicLevel)
@@ -107,6 +112,9 @@ func SetLevel(level Level) {
case DebugLevel: case DebugLevel:
curLevel = DebugLevel curLevel = DebugLevel
logrus.SetLevel(logrus.DebugLevel) logrus.SetLevel(logrus.DebugLevel)
case NilLevel:
return
} }
DebugLevel.Logf("Change Log Level to %s", logrus.GetLevel().String()) DebugLevel.Logf("Change Log Level to %s", logrus.GetLevel().String())
@@ -126,6 +134,7 @@ func setViperLogTrace() {
return return
} }
//nolint exhaustive
switch curLevel { switch curLevel {
case PanicLevel: case PanicLevel:
jwalterweatherman.SetStdoutThreshold(jwalterweatherman.LevelCritical) jwalterweatherman.SetStdoutThreshold(jwalterweatherman.LevelCritical)
@@ -144,10 +153,13 @@ func setViperLogTrace() {
case DebugLevel: case DebugLevel:
jwalterweatherman.SetStdoutThreshold(jwalterweatherman.LevelDebug) jwalterweatherman.SetStdoutThreshold(jwalterweatherman.LevelDebug)
case NilLevel:
return
} }
} }
// GetLevelString return a valid Level Type matching the given string parameter. If the given parameter don't represent a valid level, the InfoLevel will be return // GetLevelString return a valid Level Type matching the given string parameter. If the given parameter don't represent a valid level, the InfoLevel will be return.
/* /*
level the string representation of a Level type level the string representation of a Level type
*/ */
@@ -165,12 +177,14 @@ func GetLevelString(level string) Level {
case strings.ToLower(WarnLevel.String()): case strings.ToLower(WarnLevel.String()):
return WarnLevel return WarnLevel
case strings.ToLower(InfoLevel.String()):
return InfoLevel
case strings.ToLower(DebugLevel.String()): case strings.ToLower(DebugLevel.String()):
return DebugLevel return DebugLevel
default:
return InfoLevel
} }
return InfoLevel
} }
// Uint8 Convert the current Level type to a uint8 value. E.g. FatalLevel becomes 1. // Uint8 Convert the current Level type to a uint8 value. E.g. FatalLevel becomes 1.
@@ -180,6 +194,7 @@ func (level Level) Uint8() uint8 {
// String Convert the current Level type to a string. E.g. PanicLevel becomes "Critical Error". // String Convert the current Level type to a string. E.g. PanicLevel becomes "Critical Error".
func (level Level) String() string { func (level Level) String() string {
//nolint exhaustive
switch level { switch level {
case DebugLevel: case DebugLevel:
return "Debug" return "Debug"
@@ -193,12 +208,14 @@ func (level Level) String() string {
return "Fatal Error" return "Fatal Error"
case PanicLevel: case PanicLevel:
return "Critical Error" return "Critical Error"
case NilLevel:
return ""
} }
return "unknown" return "unknown"
} }
// Log Simple function to log directly the given message with the attached log Level // Log Simple function to log directly the given message with the attached log Level.
/* /*
message a string message to be logged with the attached log Level message a string message to be logged with the attached log Level
*/ */
@@ -206,7 +223,7 @@ func (level Level) Log(message string) {
level.logDetails(message, nil, nil, nil) level.logDetails(message, nil, nil, nil)
} }
// Logf Simple function to log (to the attached log Level) with a fmt function a given pattern and arguments in parameters // Logf Simple function to log (to the attached log Level) with a fmt function a given pattern and arguments in parameters.
/* /*
format a string pattern for fmt function format a string pattern for fmt function
args a list of interface to match the references in the pattern args a list of interface to match the references in the pattern
@@ -215,7 +232,7 @@ func (level Level) Logf(format string, args ...interface{}) {
level.logDetails(fmt.Sprintf(format, args...), nil, nil, nil) level.logDetails(fmt.Sprintf(format, args...), nil, nil, nil)
} }
// LogData Simple function to log directly the given message with given data with the attached log Level // LogData Simple function to log directly the given message with given data with the attached log Level.
/* /*
message a string message to be logged with the attached log Level message a string message to be logged with the attached log Level
data an interface of data to be logged with the message. (In Text format, the data will be json marshaled) data an interface of data to be logged with the message. (In Text format, the data will be json marshaled)
@@ -224,7 +241,7 @@ func (level Level) LogData(message string, data interface{}) {
level.logDetails(message, data, nil, nil) level.logDetails(message, data, nil, nil)
} }
// WithFields Simple function to log directly the given message with given fields with the attached log Level // WithFields Simple function to log directly the given message with given fields with the attached log Level.
/* /*
message a string message to be logged with the attached log Level message a string message to be logged with the attached log Level
fields a map of string key and interfaces value for a complete list of field ("field name" => value interface) fields a map of string key and interfaces value for a complete list of field ("field name" => value interface)
@@ -248,7 +265,7 @@ func (level Level) LogError(err error) bool {
return level.LogGinErrorCtx(NilLevel, "", err, nil) return level.LogGinErrorCtx(NilLevel, "", err, nil)
} }
// LogErrorCtx Function to test, log and inform about the given error object // LogErrorCtx Function to test, log and inform about the given error object.
// //
// How iot works : // How iot works :
// + when the err is a valid error, this function will : // + when the err is a valid error, this function will :
@@ -266,7 +283,7 @@ func (level Level) LogErrorCtx(levelElse Level, context string, err error) bool
return level.LogGinErrorCtx(levelElse, context, err, nil) return level.LogGinErrorCtx(levelElse, context, err, nil)
} }
// LogErrorCtxf Function to test, log and inform about the given error object, but with a context based on a pattern and matching args // LogErrorCtxf Function to test, log and inform about the given error object, but with a context based on a pattern and matching args.
// //
// How iot works : // How iot works :
// + when the err is a valid error, this function will : // + when the err is a valid error, this function will :
@@ -307,7 +324,7 @@ func (level Level) LogGinErrorCtxf(levelElse Level, contextPattern string, err e
return level.LogGinErrorCtx(levelElse, fmt.Sprintf(contextPattern, args...), err, c) return level.LogGinErrorCtx(levelElse, fmt.Sprintf(contextPattern, args...), err, c)
} }
// LogGinErrorCtx Function to test, log and inform about the given error object // LogGinErrorCtx Function to test, log and inform about the given error object.
// This function will also add an Gin Tonic Error if the c parameters is a valid GinTonic Context reference. // This function will also add an Gin Tonic Error if the c parameters is a valid GinTonic Context reference.
// //
// How iot works : // How iot works :
@@ -322,7 +339,7 @@ func (level Level) LogGinErrorCtxf(levelElse Level, contextPattern string, err e
levelElse level used if the err is nil before returning a False result levelElse level used if the err is nil before returning a False result
context a string for the context of the current test of the error context a string for the context of the current test of the error
err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false
c a valid Go GinTonic Context reference to add current error to the Gin Tonic Error Context c a valid Go GinTonic Context reference to add current error to the Gin Tonic Error Context.
*/ */
func (level Level) LogGinErrorCtx(levelElse Level, context string, err error, c *gin.Context) bool { func (level Level) LogGinErrorCtx(levelElse Level, context string, err error, c *gin.Context) bool {
if err != nil { if err != nil {
@@ -373,6 +390,7 @@ func (level Level) logDetails(message string, data interface{}, err error, field
ent.WithFields(fields) ent.WithFields(fields)
} }
//nolint exhaustive
switch curFormat { switch curFormat {
case TextFormat: case TextFormat:
if _, ok := tags[tagStack]; ok { if _, ok := tags[tagStack]; ok {
@@ -409,9 +427,16 @@ func (level Level) logDetails(message string, data interface{}, err error, field
case JsonFormat: case JsonFormat:
ent.WithFields(tags) ent.WithFields(tags)
msg = tags[tagMsg].(string) msg = tags[tagMsg].(string)
case nilFormat:
return
} }
//nolint exhaustive
switch level { switch level {
case NilLevel:
return
case DebugLevel: case DebugLevel:
ent.Debugln(msg) ent.Debugln(msg)

View File

@@ -25,22 +25,20 @@ SOFTWARE.
package logger package logger
import ( import (
"bytes"
"log" "log"
"path" "path"
"reflect" "reflect"
"runtime" "runtime"
"strconv"
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"bytes"
"strconv"
) )
const ( const (
tagStack = "stack" tagStack = "stack"
tagTime = "time" tagTime = "time"
//tagLevel = "level" //unused
tagCaller = "func" tagCaller = "func"
tagFile = "file" tagFile = "file"
tagLine = "line" tagLine = "line"
@@ -65,9 +63,8 @@ func init() {
} }
} }
// GetLogger return a golang log.logger instance linked with this main logger // GetLogger return a golang log.logger instance linked with this main logger.
// // This function is useful to keep the format, mode, color, output... same as current config.
// This function is useful to keep the format, mode, color, output... same as current config
/* /*
msgPrefixPattern a pattern prefix to identify or comment all message passed throw this log.logger instance msgPrefixPattern a pattern prefix to identify or comment all message passed throw this log.logger instance
msgPrefixArgs a list of interface to apply on pattern with a fmt function msgPrefixArgs a list of interface to apply on pattern with a fmt function
@@ -76,9 +73,8 @@ func GetLogger(lvl Level, logFlags int, msgPrefixPattern string, msgPrefixArgs .
return log.New(GetIOWriter(lvl, msgPrefixPattern, msgPrefixArgs...), "", logFlags) return log.New(GetIOWriter(lvl, msgPrefixPattern, msgPrefixArgs...), "", logFlags)
} }
// GetLogger force the default golang log.logger instance linked with this main logger // GetLogger force the default golang log.logger instance linked with this main logger.
// // This function is useful to keep the format, mode, color, output... same as current config.
// This function is useful to keep the format, mode, color, output... same as current config
/* /*
msgPrefixPattern a pattern prefix to identify or comment all message passed throw this log.logger instance msgPrefixPattern a pattern prefix to identify or comment all message passed throw this log.logger instance
msgPrefixArgs a list of interface to apply on pattern with a fmt function msgPrefixArgs a list of interface to apply on pattern with a fmt function
@@ -100,42 +96,39 @@ func Timestamp(enable bool) {
} }
// FileTrace Reconfigure the current logger to add or not the origin file/line of each message. // FileTrace Reconfigure the current logger to add or not the origin file/line of each message.
// // This option is apply for all message except info message.
// This option is apply for all message except info message
func FileTrace(enable bool) { func FileTrace(enable bool) {
filetrace = enable filetrace = enable
setViperLogTrace() setViperLogTrace()
} }
// EnableColor Reconfigure the current logger to use color in messages format. // EnableColor Reconfigure the current logger to use color in messages format.
// // This apply only for next message and only for TextFormat.
// This apply only for next message and only for TextFormat
func EnableColor() { func EnableColor() {
modeColor = true modeColor = true
updateFormatter(nilFormat) updateFormatter(nilFormat)
} }
// DisableColor Reconfigure the current logger to not use color in messages format. // DisableColor Reconfigure the current logger to not use color in messages format.
// // This apply only for next message and only for TextFormat.
// This apply only for next message and only for TextFormat
func DisableColor() { func DisableColor() {
modeColor = false modeColor = false
updateFormatter(nilFormat) updateFormatter(nilFormat)
} }
// EnableViperLog enable or not the Gin Logger configuration // EnableViperLog enable or not the Gin Logger configuration.
func EnableViperLog(enable bool) { func EnableViperLog(enable bool) {
enableVPR = enable enableVPR = enable
setViperLogTrace() setViperLogTrace()
} }
// SetTracePathFilter customize the filter apply to filepath on trace // SetTracePathFilter customize the filter apply to filepath on trace.
func SetTracePathFilter(path string) { func SetTracePathFilter(path string) {
filterPkg = path filterPkg = path
} }
func getFrame() runtime.Frame { func getFrame() runtime.Frame {
// Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need // Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need.
programCounters := make([]uintptr, 10, 255) programCounters := make([]uintptr, 10, 255)
n := runtime.Callers(1, programCounters) n := runtime.Callers(1, programCounters)

View File

@@ -30,7 +30,6 @@ import (
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/nabbar/golib/errors" "github.com/nabbar/golib/errors"
"github.com/nabbar/golib/logger" "github.com/nabbar/golib/logger"
) )

View File

@@ -52,16 +52,24 @@ func getMessage(code errors.CodeError) (message string) {
switch code { switch code {
case EMPTY_PARAMS: case EMPTY_PARAMS:
return "given parameters is empty" return "given parameters is empty"
case HEADER_AUTH_MISSING: case HEADER_AUTH_MISSING:
return "missing authorization header" return "missing authorization header"
case HEADER_AUTH_EMPTY: case HEADER_AUTH_EMPTY:
return "authorization header is empty" return "authorization header is empty"
case HEADER_AUTH_REQUIRE: case HEADER_AUTH_REQUIRE:
return "authorization check failed, authorization still require" return "authorization check failed, authorization still require"
case HEADER_AUTH_FORBIDDEN: case HEADER_AUTH_FORBIDDEN:
return "authorization check success but unauthorized client" return "authorization check success but unauthorized client"
case HEADER_AUTH_ERROR: case HEADER_AUTH_ERROR:
return "authorization check return an invalid response code" return "authorization check return an invalid response code"
case errors.UNK_ERROR:
return ""
} }
return "" return ""

View File

@@ -38,7 +38,7 @@ func init() {
} }
} }
// SetGinHandler func that return given func as ginTonic HandlerFunc interface type // SetGinHandler func that return given func as ginTonic HandlerFunc interface type.
func SetGinHandler(fct func(c *gin.Context)) gin.HandlerFunc { func SetGinHandler(fct func(c *gin.Context)) gin.HandlerFunc {
return fct return fct
} }

View File

@@ -49,16 +49,24 @@ func init() {
func getMessage(code errors.CodeError) (message string) { func getMessage(code errors.CodeError) (message string) {
switch code { switch code {
case EMPTY_PARAMS: case EMPTY_PARAMS:
return "given parameters is empty" return "given parameters is empty"
case EMPTY_PACKED: case EMPTY_PACKED:
return "packed file is empty" return "packed file is empty"
case INDEX_NOT_FOUND: case INDEX_NOT_FOUND:
return "mode index is defined but index.(html|htm) is not found" return "mode index is defined but index.(html|htm) is not found"
case INDEX_REQUESTED_NOT_SET: case INDEX_REQUESTED_NOT_SET:
return "request call index but mode index is false" return "request call index but mode index is false"
case FILE_NOT_FOUND: case FILE_NOT_FOUND:
return "requested packed file is not found" return "requested packed file is not found"
case errors.UNK_ERROR:
return ""
} }
return "" return ""

View File

@@ -36,10 +36,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/render" "github.com/gin-gonic/gin/render"
"github.com/gobuffalo/packr" "github.com/gobuffalo/packr"
"github.com/nabbar/golib/errors" "github.com/nabbar/golib/errors"
"github.com/nabbar/golib/logger" "github.com/nabbar/golib/logger"
"github.com/nabbar/golib/router" "github.com/nabbar/golib/router"
) )