fix golint issues in core/logx (#496)

master
Kevin Wan 4 years ago committed by GitHub
parent dac00d10c1
commit 226513ed60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,5 +1,6 @@
package logx package logx
// A LogConf is a logging config.
type LogConf struct { type LogConf struct {
ServiceName string `json:",optional"` ServiceName string `json:",optional"`
Mode string `json:",default=console,options=console|file|volume"` Mode string `json:",default=console,options=console|file|volume"`

@ -12,6 +12,7 @@ const durationCallerDepth = 3
type durationLogger logEntry type durationLogger logEntry
// WithDuration returns a Logger which logs the given duration.
func WithDuration(d time.Duration) Logger { func WithDuration(d time.Duration) Logger {
return &durationLogger{ return &durationLogger{
Duration: timex.ReprOfDuration(d), Duration: timex.ReprOfDuration(d),

@ -1,21 +1,25 @@
package logx package logx
// A LessLogger is a logger that control to log once during the given duration.
type LessLogger struct { type LessLogger struct {
*limitedExecutor *limitedExecutor
} }
// NewLessLogger returns a LessLogger.
func NewLessLogger(milliseconds int) *LessLogger { func NewLessLogger(milliseconds int) *LessLogger {
return &LessLogger{ return &LessLogger{
limitedExecutor: newLimitedExecutor(milliseconds), limitedExecutor: newLimitedExecutor(milliseconds),
} }
} }
// Error logs v into error log or discard it if more than once in the given duration.
func (logger *LessLogger) Error(v ...interface{}) { func (logger *LessLogger) Error(v ...interface{}) {
logger.logOrDiscard(func() { logger.logOrDiscard(func() {
Error(v...) Error(v...)
}) })
} }
// Errorf logs v with format into error log or discard it if more than once in the given duration.
func (logger *LessLogger) Errorf(format string, v ...interface{}) { func (logger *LessLogger) Errorf(format string, v ...interface{}) {
logger.logOrDiscard(func() { logger.logOrDiscard(func() {
Errorf(format, v...) Errorf(format, v...)

@ -7,7 +7,7 @@ type lessWriter struct {
writer io.Writer writer io.Writer
} }
func NewLessWriter(writer io.Writer, milliseconds int) *lessWriter { func newLessWriter(writer io.Writer, milliseconds int) *lessWriter {
return &lessWriter{ return &lessWriter{
limitedExecutor: newLimitedExecutor(milliseconds), limitedExecutor: newLimitedExecutor(milliseconds),
writer: writer, writer: writer,

@ -9,7 +9,7 @@ import (
func TestLessWriter(t *testing.T) { func TestLessWriter(t *testing.T) {
var builder strings.Builder var builder strings.Builder
w := NewLessWriter(&builder, 500) w := newLessWriter(&builder, 500)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
_, err := w.Write([]byte("hello")) _, err := w.Write([]byte("hello"))
assert.Nil(t, err) assert.Nil(t, err)

@ -57,8 +57,11 @@ const (
) )
var ( var (
ErrLogPathNotSet = errors.New("log path must be set") // ErrLogPathNotSet is an error that indicates the log path is not set.
ErrLogNotInitialized = errors.New("log not initialized") ErrLogPathNotSet = errors.New("log path must be set")
// ErrLogNotInitialized is an error that log is not initialized.
ErrLogNotInitialized = errors.New("log not initialized")
// ErrLogServiceNameNotSet is an error that indicates that the service name is not set.
ErrLogServiceNameNotSet = errors.New("log service name must be set") ErrLogServiceNameNotSet = errors.New("log service name must be set")
writeConsole bool writeConsole bool
@ -89,8 +92,10 @@ type (
keepDays int keepDays int
} }
// LogOption defines the method to customize the logging.
LogOption func(options *logOptions) LogOption func(options *logOptions)
// A Logger represents a logger.
Logger interface { Logger interface {
Error(...interface{}) Error(...interface{})
Errorf(string, ...interface{}) Errorf(string, ...interface{})
@ -102,6 +107,7 @@ type (
} }
) )
// MustSetup sets up logging with given config c. It exits on error.
func MustSetup(c LogConf) { func MustSetup(c LogConf) {
Must(SetUp(c)) Must(SetUp(c))
} }
@ -122,10 +128,12 @@ func SetUp(c LogConf) error {
} }
} }
// Alert alerts v in alert level, and the message is written to error log.
func Alert(v string) { func Alert(v string) {
output(errorLog, levelAlert, v) output(errorLog, levelAlert, v)
} }
// Close closes the logging.
func Close() error { func Close() error {
if writeConsole { if writeConsole {
return nil return nil
@ -170,6 +178,7 @@ func Close() error {
return nil return nil
} }
// Disable disables the logging.
func Disable() { func Disable() {
once.Do(func() { once.Do(func() {
atomic.StoreUint32(&initialized, 1) atomic.StoreUint32(&initialized, 1)
@ -183,40 +192,49 @@ func Disable() {
}) })
} }
// Error writes v into error log.
func Error(v ...interface{}) { func Error(v ...interface{}) {
ErrorCaller(1, v...) ErrorCaller(1, v...)
} }
// Errorf writes v with format into error log.
func Errorf(format string, v ...interface{}) { func Errorf(format string, v ...interface{}) {
ErrorCallerf(1, format, v...) ErrorCallerf(1, format, v...)
} }
// ErrorCaller writes v with context into error log.
func ErrorCaller(callDepth int, v ...interface{}) { func ErrorCaller(callDepth int, v ...interface{}) {
errorSync(fmt.Sprint(v...), callDepth+callerInnerDepth) errorSync(fmt.Sprint(v...), callDepth+callerInnerDepth)
} }
// ErrorCallerf writes v with context in format into error log.
func ErrorCallerf(callDepth int, format string, v ...interface{}) { func ErrorCallerf(callDepth int, format string, v ...interface{}) {
errorSync(fmt.Sprintf(format, v...), callDepth+callerInnerDepth) errorSync(fmt.Sprintf(format, v...), callDepth+callerInnerDepth)
} }
// ErrorStack writes v along with call stack into error log.
func ErrorStack(v ...interface{}) { func ErrorStack(v ...interface{}) {
// there is newline in stack string // there is newline in stack string
stackSync(fmt.Sprint(v...)) stackSync(fmt.Sprint(v...))
} }
// ErrorStackf writes v along with call stack in format into error log.
func ErrorStackf(format string, v ...interface{}) { func ErrorStackf(format string, v ...interface{}) {
// there is newline in stack string // there is newline in stack string
stackSync(fmt.Sprintf(format, v...)) stackSync(fmt.Sprintf(format, v...))
} }
// Info writes v into access log.
func Info(v ...interface{}) { func Info(v ...interface{}) {
infoSync(fmt.Sprint(v...)) infoSync(fmt.Sprint(v...))
} }
// Infof writes v with format into access log.
func Infof(format string, v ...interface{}) { func Infof(format string, v ...interface{}) {
infoSync(fmt.Sprintf(format, v...)) infoSync(fmt.Sprintf(format, v...))
} }
// Must checks if err is nil, otherwise logs the err and exits.
func Must(err error) { func Must(err error) {
if err != nil { if err != nil {
msg := formatWithCaller(err.Error(), 3) msg := formatWithCaller(err.Error(), 3)
@ -226,46 +244,56 @@ func Must(err error) {
} }
} }
// SetLevel sets the logging level. It can be used to suppress some logs.
func SetLevel(level uint32) { func SetLevel(level uint32) {
atomic.StoreUint32(&logLevel, level) atomic.StoreUint32(&logLevel, level)
} }
// Severe writes v into severe log.
func Severe(v ...interface{}) { func Severe(v ...interface{}) {
severeSync(fmt.Sprint(v...)) severeSync(fmt.Sprint(v...))
} }
// Severef writes v with format into severe log.
func Severef(format string, v ...interface{}) { func Severef(format string, v ...interface{}) {
severeSync(fmt.Sprintf(format, v...)) severeSync(fmt.Sprintf(format, v...))
} }
// Slow writes v into slow log.
func Slow(v ...interface{}) { func Slow(v ...interface{}) {
slowSync(fmt.Sprint(v...)) slowSync(fmt.Sprint(v...))
} }
// Slowf writes v with format into slow log.
func Slowf(format string, v ...interface{}) { func Slowf(format string, v ...interface{}) {
slowSync(fmt.Sprintf(format, v...)) slowSync(fmt.Sprintf(format, v...))
} }
// Stat writes v into stat log.
func Stat(v ...interface{}) { func Stat(v ...interface{}) {
statSync(fmt.Sprint(v...)) statSync(fmt.Sprint(v...))
} }
// Statf writes v with format into stat log.
func Statf(format string, v ...interface{}) { func Statf(format string, v ...interface{}) {
statSync(fmt.Sprintf(format, v...)) statSync(fmt.Sprintf(format, v...))
} }
// WithCooldownMillis customizes logging on writting call stack interval.
func WithCooldownMillis(millis int) LogOption { func WithCooldownMillis(millis int) LogOption {
return func(opts *logOptions) { return func(opts *logOptions) {
opts.logStackCooldownMills = millis opts.logStackCooldownMills = millis
} }
} }
// WithKeepDays customizes logging to keep logs with days.
func WithKeepDays(days int) LogOption { func WithKeepDays(days int) LogOption {
return func(opts *logOptions) { return func(opts *logOptions) {
opts.keepDays = days opts.keepDays = days
} }
} }
// WithGzip customizes logging to automatically gzip the log files.
func WithGzip() LogOption { func WithGzip() LogOption {
return func(opts *logOptions) { return func(opts *logOptions) {
opts.gzipEnabled = true opts.gzipEnabled = true
@ -382,7 +410,7 @@ func setupWithConsole(c LogConf) {
errorLog = newLogWriter(log.New(os.Stderr, "", flags)) errorLog = newLogWriter(log.New(os.Stderr, "", flags))
severeLog = newLogWriter(log.New(os.Stderr, "", flags)) severeLog = newLogWriter(log.New(os.Stderr, "", flags))
slowLog = newLogWriter(log.New(os.Stderr, "", flags)) slowLog = newLogWriter(log.New(os.Stderr, "", flags))
stackLog = NewLessWriter(errorLog, options.logStackCooldownMills) stackLog = newLessWriter(errorLog, options.logStackCooldownMills)
statLog = infoLog statLog = infoLog
}) })
} }
@ -434,7 +462,7 @@ func setupWithFiles(c LogConf) error {
return return
} }
stackLog = NewLessWriter(errorLog, options.logStackCooldownMills) stackLog = newLessWriter(errorLog, options.logStackCooldownMills)
}) })
return err return err

@ -26,9 +26,11 @@ const (
defaultFileMode = 0600 defaultFileMode = 0600
) )
// ErrLogFileClosed is an error that indicates the log file is already closed.
var ErrLogFileClosed = errors.New("error: log file closed") var ErrLogFileClosed = errors.New("error: log file closed")
type ( type (
// A RotateRule interface is used to define the log rotating rules.
RotateRule interface { RotateRule interface {
BackupFileName() string BackupFileName() string
MarkRotated() MarkRotated()
@ -36,6 +38,7 @@ type (
ShallRotate() bool ShallRotate() bool
} }
// A RotateLogger is a Logger that can rotate log files with given rules.
RotateLogger struct { RotateLogger struct {
filename string filename string
backup string backup string
@ -50,6 +53,7 @@ type (
closeOnce sync.Once closeOnce sync.Once
} }
// A DailyRotateRule is a rule to daily rotate the log files.
DailyRotateRule struct { DailyRotateRule struct {
rotatedTime string rotatedTime string
filename string filename string
@ -59,6 +63,7 @@ type (
} }
) )
// DefaultRotateRule is a default log rotating rule, currently DailyRotateRule.
func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRule { func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRule {
return &DailyRotateRule{ return &DailyRotateRule{
rotatedTime: getNowDate(), rotatedTime: getNowDate(),
@ -69,14 +74,17 @@ func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRu
} }
} }
// BackupFileName returns the backup filename on rotating.
func (r *DailyRotateRule) BackupFileName() string { func (r *DailyRotateRule) BackupFileName() string {
return fmt.Sprintf("%s%s%s", r.filename, r.delimiter, getNowDate()) return fmt.Sprintf("%s%s%s", r.filename, r.delimiter, getNowDate())
} }
// MarkRotated marks the rotated time of r to be the current time.
func (r *DailyRotateRule) MarkRotated() { func (r *DailyRotateRule) MarkRotated() {
r.rotatedTime = getNowDate() r.rotatedTime = getNowDate()
} }
// OutdatedFiles returns the files that exceeded the keeping days.
func (r *DailyRotateRule) OutdatedFiles() []string { func (r *DailyRotateRule) OutdatedFiles() []string {
if r.days <= 0 { if r.days <= 0 {
return nil return nil
@ -113,10 +121,12 @@ func (r *DailyRotateRule) OutdatedFiles() []string {
return outdates return outdates
} }
// ShallRotate checks if the file should be rotated.
func (r *DailyRotateRule) ShallRotate() bool { func (r *DailyRotateRule) ShallRotate() bool {
return len(r.rotatedTime) > 0 && getNowDate() != r.rotatedTime return len(r.rotatedTime) > 0 && getNowDate() != r.rotatedTime
} }
// NewLogger returns a RotateLogger with given filename and rule, etc.
func NewLogger(filename string, rule RotateRule, compress bool) (*RotateLogger, error) { func NewLogger(filename string, rule RotateRule, compress bool) (*RotateLogger, error) {
l := &RotateLogger{ l := &RotateLogger{
filename: filename, filename: filename,
@ -133,6 +143,7 @@ func NewLogger(filename string, rule RotateRule, compress bool) (*RotateLogger,
return l, nil return l, nil
} }
// Close closes l.
func (l *RotateLogger) Close() error { func (l *RotateLogger) Close() error {
var err error var err error

@ -67,6 +67,7 @@ func (l *traceLogger) write(writer io.Writer, level, content string) {
outputJson(writer, l) outputJson(writer, l)
} }
// WithContext sets ctx to log, for keeping tracing infomation.
func WithContext(ctx context.Context) Logger { func WithContext(ctx context.Context) Logger {
return &traceLogger{ return &traceLogger{
ctx: ctx, ctx: ctx,

@ -13,8 +13,8 @@ import (
) )
const ( const (
mockTraceId = "mock-trace-id" mockTraceID = "mock-trace-id"
mockSpanId = "mock-span-id" mockSpanID = "mock-span-id"
) )
var mock tracespec.Trace = new(mockTrace) var mock tracespec.Trace = new(mockTrace)
@ -24,8 +24,8 @@ func TestTraceLog(t *testing.T) {
atomic.StoreUint32(&initialized, 1) atomic.StoreUint32(&initialized, 1)
ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock)
WithContext(ctx).(*traceLogger).write(&buf, levelInfo, testlog) WithContext(ctx).(*traceLogger).write(&buf, levelInfo, testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
} }
func TestTraceError(t *testing.T) { func TestTraceError(t *testing.T) {
@ -36,12 +36,12 @@ func TestTraceError(t *testing.T) {
l := WithContext(ctx).(*traceLogger) l := WithContext(ctx).(*traceLogger)
SetLevel(InfoLevel) SetLevel(InfoLevel)
l.WithDuration(time.Second).Error(testlog) l.WithDuration(time.Second).Error(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
buf.Reset() buf.Reset()
l.WithDuration(time.Second).Errorf(testlog) l.WithDuration(time.Second).Errorf(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
} }
func TestTraceInfo(t *testing.T) { func TestTraceInfo(t *testing.T) {
@ -52,12 +52,12 @@ func TestTraceInfo(t *testing.T) {
l := WithContext(ctx).(*traceLogger) l := WithContext(ctx).(*traceLogger)
SetLevel(InfoLevel) SetLevel(InfoLevel)
l.WithDuration(time.Second).Info(testlog) l.WithDuration(time.Second).Info(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
buf.Reset() buf.Reset()
l.WithDuration(time.Second).Infof(testlog) l.WithDuration(time.Second).Infof(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
} }
func TestTraceSlow(t *testing.T) { func TestTraceSlow(t *testing.T) {
@ -68,12 +68,12 @@ func TestTraceSlow(t *testing.T) {
l := WithContext(ctx).(*traceLogger) l := WithContext(ctx).(*traceLogger)
SetLevel(InfoLevel) SetLevel(InfoLevel)
l.WithDuration(time.Second).Slow(testlog) l.WithDuration(time.Second).Slow(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
buf.Reset() buf.Reset()
l.WithDuration(time.Second).Slowf(testlog) l.WithDuration(time.Second).Slowf(testlog)
assert.True(t, strings.Contains(buf.String(), mockTraceId)) assert.True(t, strings.Contains(buf.String(), mockTraceID))
assert.True(t, strings.Contains(buf.String(), mockSpanId)) assert.True(t, strings.Contains(buf.String(), mockSpanID))
} }
func TestTraceWithoutContext(t *testing.T) { func TestTraceWithoutContext(t *testing.T) {
@ -83,22 +83,22 @@ func TestTraceWithoutContext(t *testing.T) {
l := WithContext(context.Background()).(*traceLogger) l := WithContext(context.Background()).(*traceLogger)
SetLevel(InfoLevel) SetLevel(InfoLevel)
l.WithDuration(time.Second).Info(testlog) l.WithDuration(time.Second).Info(testlog)
assert.False(t, strings.Contains(buf.String(), mockTraceId)) assert.False(t, strings.Contains(buf.String(), mockTraceID))
assert.False(t, strings.Contains(buf.String(), mockSpanId)) assert.False(t, strings.Contains(buf.String(), mockSpanID))
buf.Reset() buf.Reset()
l.WithDuration(time.Second).Infof(testlog) l.WithDuration(time.Second).Infof(testlog)
assert.False(t, strings.Contains(buf.String(), mockTraceId)) assert.False(t, strings.Contains(buf.String(), mockTraceID))
assert.False(t, strings.Contains(buf.String(), mockSpanId)) assert.False(t, strings.Contains(buf.String(), mockSpanID))
} }
type mockTrace struct{} type mockTrace struct{}
func (t mockTrace) TraceId() string { func (t mockTrace) TraceId() string {
return mockTraceId return mockTraceID
} }
func (t mockTrace) SpanId() string { func (t mockTrace) SpanId() string {
return mockSpanId return mockSpanID
} }
func (t mockTrace) Finish() { func (t mockTrace) Finish() {

Loading…
Cancel
Save