dragfire
dragfire

Reputation: 443

Implement a minimal logger in Golang

I've created a minimal logger in Golang. I tried to keep it as simple as possible but two problems arise:

CMD

Here's my code:

package logger

import (
    "log"
    "os"
)

var (
    dlog = log.New(os.Stdout, "\x1B[36mDEBUG: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    wlog = log.New(os.Stdout, "\x1B[35mWARN: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    ilog = log.New(os.Stdout, "\x1B[32mINFO: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    elog = log.New(os.Stderr, "\x1B[31mERROR: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
)

// Debug Log
func Debug(a ...interface{}) {
     dlog.Println(a)
}

// Warn log
func Warn(a ...interface{}) {
    wlog.Println(a)
}

// Info Log
func Info(a ...interface{}) {
    ilog.Println(a)
}

// Error Log
func Error(a ...interface{}) {
    elog.Println(a)
}

I use them like this: logger.Debug("Hello") or logger.Info("There")

How do I implement this correctly? Thank you.

Upvotes: 0

Views: 674

Answers (1)

Thundercat
Thundercat

Reputation: 121119

Println is passed a single parameter, a slice of interface{}, and prints it using slice notation. To fix this, pass the variadic parameters to your functions as variadic arguments to the called functions.

func Debug(a ...interface{}) {
     dlog.Println(a...) // <-- note ... here
}

Here's the doc on variadic args.

Call Output to workaround the file name issue.

func Debug(a ...interface{}) {
     dlog.Output(2, fmt.Sprintln(a...))
}

Upvotes: 3

Related Questions