A minimal level based logging library for Go.
go get github.com/IchBinLeoon/slogx
package main
import "github.com/IchBinLeoon/slogx"
func main() {
logger := slogx.NewLogger("EXAMPLE")
logger.Error("This is Error!")
logger.Errorf("This is %s!", "Error")
logger.Warning("This is Warning!")
logger.Warningf("This is %s!", "Warning")
logger.Info("This is Info!")
logger.Infof("This is %s!", "Info")
}Output:
2021-06-08 20:08:19 ERROR main.go:11 EXAMPLE: This is Error!
2021-06-08 20:08:19 ERROR main.go:12 EXAMPLE: This is Error!
2021-06-08 20:08:19 WARNING main.go:14 EXAMPLE: This is Warning!
2021-06-08 20:08:19 WARNING main.go:15 EXAMPLE: This is Warning!
2021-06-08 20:08:19 INFO main.go:17 EXAMPLE: This is Info!
2021-06-08 20:08:19 INFO main.go:18 EXAMPLE: This is Info!
Create a new logger:
logger := slogx.NewLogger("awesome name")Get an existing logger by its name:
logger := slogx.GetLogger("awesome name")Log a message at Fatal level and exit:
logger.Fatal("This is Fatal!")
logger.Fatalf("This is %s!", "Fatal")Log a message at Error level:
logger.Error("This is Error!")
logger.Errorf("This is %s!", "Error")Log a message at Warning level:
logger.Warning("This is Warning!")
logger.Warningf("This is %s!", "Warning")Log a message at Info level:
logger.Info("This is Info!")
logger.Infof("This is %s!", "Info")Log a message at Debug level:
logger.Debug("This is Debug!")
logger.Debugf("This is %s!", "Debug")Log a message at a specified level:
logger.Log(slogx.ERROR, "This is Error!")
logger.Logf(slogx.INFO, "This is %s!", "Info")The default logging level is INFO.
Set the logging level:
logger.SetLevel(slogx.DEBUG)Set the logging level from a string:
logger.SetLevel(slogx.ParseLevel("DEBUG"))Get the current logging level:
level := logger.GetLevel()Set a custom format:
err := logger.SetFormat("[${time}] ${file} (${level}): ${message}")
if err != nil {
// Handle error...
}| Verb | Description |
|---|---|
| ${time} | The current time |
| ${level} | The logging level |
| ${file} | The file the log statement is in |
| ${line} | The line the log statement is on |
| ${name} | The name of the logger |
| ${message} | The log message |
The default time format is 2006-01-02 15:04:05.
To change the time format:
logger.SetTimeFormat("Jan _2 15:04:05")The time format must be a layout supported by the go time package.
The default output is Stdout.
Set the output:
f, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
// Handle error...
}
defer f.Close()
logger.SetOutput(f)The output can be any io.Writer.
Contributions are welcome! Feel free to open issues or submit pull requests!
This project is licensed under the MIT License. See the LICENSE file for more details.