Skip to content

Commit

Permalink
Linter fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasmalkmus committed Mar 24, 2021
1 parent fb977ef commit 9ff9576
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 79 deletions.
3 changes: 1 addition & 2 deletions consolewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func init() {
}

pName := path.Base(os.Args[0])
if strings.HasPrefix(os.Args[0], path.Join(os.TempDir(), "go-build")) && strings.HasSuffix(os.Args[0], ".test") == false {
if strings.HasPrefix(os.Args[0], path.Join(os.TempDir(), "go-build")) && !strings.HasSuffix(os.Args[0], ".test") {
// check to see if the executing program is /tmp/go-build<numbers>/whatever
// which generally means this is a go run type thing
// in this case the pName we can get is just a long annoying hash
Expand Down Expand Up @@ -89,7 +89,6 @@ func (w *ConsoleWriter) BuildTheme(module string) ColorTheme {

// Log ...
func (w *ConsoleWriter) Log(level Level, theme ColorTheme, module, filename string, line int, timestamp time.Time, message string) {

ts := timestamp.In(time.UTC).Format("15:04:05.00")
filename = filepath.Base(filename)

Expand Down
27 changes: 15 additions & 12 deletions diskwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,18 @@ type DiskWriter struct {
}

// rotateLogs will rotate the current logs and return the next rotation time
// nolint
func (w DiskWriter) rotateLogs() (time.Time, error) {
if _, err := os.Stat(w.logpath); err != nil {
// no log to rotate yet
os.MkdirAll(path.Dir(w.logpath), 0777)
if f, err := os.Create(w.logpath); err != nil {
_ = os.MkdirAll(path.Dir(w.logpath), 0777)

f, err := os.Create(w.logpath)
if err != nil {
return time.Time{}, err
} else {
f.Close()
return time.Now().Add(w.RotateDuration), nil
}
defer f.Close()

return time.Now().Add(w.RotateDuration), nil
}

logfiles := []string{path.Base(w.logpath)}
Expand All @@ -56,20 +57,22 @@ func (w DiskWriter) rotateLogs() (time.Time, error) {
oldName := logfiles[i]
newName := fmt.Sprintf("%s.%d", path.Base(w.logpath), i+1)

os.Rename(path.Join(logDir, oldName), path.Join(logDir, newName))
_ = os.Rename(path.Join(logDir, oldName), path.Join(logDir, newName))

if i >= w.MaximumLogFiles-1 {
os.Remove(path.Join(logDir, newName))
}
}

os.MkdirAll(path.Dir(w.logpath), 0777)
if f, err := os.Create(w.logpath); err != nil {
_ = os.MkdirAll(path.Dir(w.logpath), 0777)

f, err := os.Create(w.logpath)
if err != nil {
return time.Time{}, err
} else {
f.Close()
return time.Now().Add(w.RotateDuration), nil
}
defer f.Close()

return time.Now().Add(w.RotateDuration), nil
}

func writeAll(writer io.Writer, buf []byte) error {
Expand Down
2 changes: 1 addition & 1 deletion diskwriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestDiskWriter(t *testing.T) {
marker3 := "i am potato"

tmpDir, err := ioutil.TempDir(os.TempDir(), "testdiskwriter")
defer os.RemoveAll(tmpDir) // nolint
defer os.RemoveAll(tmpDir)
require.NoError(err)

logPath := path.Join(tmpDir, "logfile.log")
Expand Down
33 changes: 17 additions & 16 deletions logmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,12 @@ type writeDescriptor struct {
// GetLogger will get a logger for the specified name
func GetLogger(name string) Logger {
// go through the loggerSpec and look for "Foo=Trace" or whatever
// it will always prefer longer module names that match but also match smaller ones
// for example, for module name foo.bar.baz, foo.bar=Trace will match but foo.bar.baz=Trace will be prefered
// it's not smart enough to figure out that foo.bar.ba should be ignored in preference of foo.bar
// but that is a compromise that i'm willing to make for simplicity and flexability
// it will always prefer longer module names that match but also match
// smaller ones for example, for module name foo.bar.baz, foo.bar=Trace will
// match but foo.bar.baz=Trace will be preferred it's not smart enough to
// figure out that foo.bar.ba should be ignored in preference of foo.bar but
// that is a compromise that i'm willing to make for simplicity and
// flexability
level := Info
levelHint := ""
for _, moduleInfo := range strings.Split(loggerSpec, ":") {
Expand Down Expand Up @@ -225,7 +227,7 @@ func (l *Logger) buildDescriptors() {
// Log ...
func (l *Logger) Log(level Level, message string, args ...interface{}) {
// safe if not called before writers are added
if atomic.CompareAndSwapUint32(&l.themeGenerated, 0, 1) == true {
if atomic.CompareAndSwapUint32(&l.themeGenerated, 0, 1) {
l.buildDescriptors()
}

Expand All @@ -235,7 +237,7 @@ func (l *Logger) Log(level Level, message string, args ...interface{}) {

ts := time.Now().UTC()
_, filepath, line, ok := runtime.Caller(2)
if ok == true {
if ok {
filepath = path.Base(filepath)
} else {
filepath = "__unknown__"
Expand Down Expand Up @@ -270,7 +272,6 @@ func (l *Logger) JSONifyIndent(v interface{}) string {
return fmt.Sprintf("ERRMARSHALLING=%s", err)
}
return string(b)

}

// IsError is a good replacement for if err != nil {
Expand All @@ -280,20 +281,20 @@ func (l *Logger) JSONifyIndent(v interface{}) string {
func (l *Logger) IsError(err error) bool {
if err == nil {
return false
} else {
msg := SPrintStack(3, 8)
msg += fmt.Sprintf("Detected error: %v\n", err)
l.Log(Error, msg)

return true
}

msg := SPrintStack(3, 8)
msg += fmt.Sprintf("Detected error: %v\n", err)
l.Log(Error, msg)

return true
}

type stringer interface {
String() string
}

// Recover is intended to be used when recovering from panics, it will function similiarly to IsError
// Recover is intended to be used when recovering from panics, it will function similarly to IsError
// in that it will output a stacktrace, but it has additional handling to strip out the panic stack
// err is interface{} for convenience as that is what you will receieve from recover()
// example:
Expand Down Expand Up @@ -325,7 +326,7 @@ func (l *Logger) Recover(v interface{}) error {
}

if err == nil {
err = fmt.Errorf("Unknown panic error: %v", v)
err = fmt.Errorf("unknown panic error: %v", v)
}

msg := SPrintStack(5, maxCallers)
Expand Down Expand Up @@ -444,7 +445,7 @@ func SPrintStack(skip, max int) string {
frames := runtime.CallersFrames(callers)
foundFrames := 0
more := true
for more == true && foundFrames <= max {
for more && foundFrames <= max {
var frame runtime.Frame
frame, more = frames.Next()

Expand Down
8 changes: 4 additions & 4 deletions logmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestLookAtTheLogFormat(t *testing.T) {
logger.Debug("test debug")
logger.Info("test info")
logger.Warn("test warning")
logger.Error("test error")
_ = logger.Error("test error")
logger.Critical("test critical")
wg.Done()
}(log)
Expand Down Expand Up @@ -81,18 +81,18 @@ func TestRecover(t *testing.T) {
}()

panicfunc()
return //nolint(vet)
return
}

checkPanicErr := func() error { return check(func() { panic(errors.New("oh no")) }) }
checkPanicString := func() error { return check(func() { panic("oh no") }) }
checkNoPanic := func() error { return check(func() {}) }

require.NotPanics(func() { checkPanicErr() })
require.NotPanics(func() { _ = checkPanicErr() })
assert.EqualError(checkPanicErr(), "oh no")
assert.EqualError(checkPanicString(), "oh no")

require.NotPanics(func() { checkNoPanic() })
require.NotPanics(func() { _ = checkNoPanic() })
assert.NoError(checkNoPanic())
}

Expand Down
55 changes: 11 additions & 44 deletions syslogwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ const rfc5424 = "2006-01-02T15:04:05.000Z07:00"

var utf8bom = []byte{0xef, 0xbb, 0xbf}

// Most of this code imitates the golang syslog implimentation
// Most of this code imitates the golang syslog implementation
// but as a lot of that is hard-coded to use specific (poor) formatting
// we re-impliment
// we re-implement

// Taken from the go stdlib implimentation of syslog
// Taken from the go stdlib implementation of syslog
// modified to not export values
// nolint
//nolint:deadcode,varcheck // Maybe they get used at some point.
const (
// Severity.

Expand All @@ -37,38 +37,6 @@ const (
logDebug
)

// nolint
const (
// Facility.

// From /usr/include/sys/syslog.h.
// These are the same up to LOG_FTP on Linux, BSD, and OS X.
logKern int = iota << 3
logUser
logMail
logDaemon
logAuth
logSyslog
logLpr
logNews
logUucp
logCron
logAuthpriv
logFtp
_ // unused
_ // unused
_ // unused
_ // unused
logLocal0
logLocal1
logLocal2
logLocal3
logLocal4
logLocal5
logLocal6
logLocal7
)

// a sub-interface of net.Conn, makes mocking simpler in tests
type connwriter interface {
Close() error
Expand All @@ -91,7 +59,7 @@ func unixSyslog() (conn connwriter, err error) {
}
}
}
return nil, errors.New("Unix syslog delivery error")
return nil, errors.New("unix syslog delivery error")
}

// SyslogWriter ...
Expand Down Expand Up @@ -133,7 +101,7 @@ func (w *SyslogWriter) connect() (err error) {
w.m.Lock()
defer w.m.Unlock()
if w.conn != nil {
w.conn.Close() // nolint
w.conn.Close()
w.conn = nil
}

Expand Down Expand Up @@ -171,13 +139,13 @@ func (w *SyslogWriter) sendloop() {

for {
ok := w.sendBufferedMessages()
if ok == false {
if ok {
// network connection problem, backoff for a while to stop any hammering
if backoffCounter < 7 {
backoffCounter++
}

<-time.After((time.Millisecond * 50) * time.Duration(rand.Int31n(backoffCounter)))
<-time.After((time.Millisecond * 50) * time.Duration(rand.Int31n(backoffCounter))) //nolint:gosec // This is fine here.
}

for len(w.bufferedMessages) < 1 {
Expand All @@ -187,7 +155,6 @@ func (w *SyslogWriter) sendloop() {
}
}
}

}

func (w *SyslogWriter) sendBufferedMessages() (ok bool) {
Expand All @@ -200,8 +167,8 @@ func (w *SyslogWriter) sendBufferedMessages() (ok bool) {
break
}
}
if ok == false {
defer w.connect() // nolint
if ok {
defer w.connect() //nolint:errcheck // If it fails, it fails...
}
return
}
Expand Down Expand Up @@ -238,7 +205,7 @@ func (w *SyslogWriter) Log(level Level, _ ColorTheme, module, filename string, l
}

hostname := "-"
if w.localConn == false {
if w.localConn {
hostname = w.hostname
}

Expand Down

0 comments on commit 9ff9576

Please sign in to comment.