2022-09-27 07:35:34 +00:00
|
|
|
package logs
|
|
|
|
|
|
|
|
import (
|
2023-04-06 13:13:02 +00:00
|
|
|
"fmt"
|
2023-04-07 14:59:07 +00:00
|
|
|
"github.com/fthvgb1/wp-go/internal/pkg/config"
|
|
|
|
"github.com/fthvgb1/wp-go/safety"
|
|
|
|
"io"
|
2022-09-27 07:35:34 +00:00
|
|
|
"log"
|
2023-04-07 14:59:07 +00:00
|
|
|
"os"
|
2023-04-06 13:13:02 +00:00
|
|
|
"runtime"
|
2022-09-27 07:35:34 +00:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-04-07 14:59:07 +00:00
|
|
|
var logs = safety.NewVar[*log.Logger](nil)
|
2023-04-09 13:51:12 +00:00
|
|
|
var logFile = safety.NewVar[*os.File](nil)
|
2023-04-07 14:59:07 +00:00
|
|
|
|
|
|
|
func InitLogger() error {
|
2023-04-09 13:51:12 +00:00
|
|
|
preFD := logFile.Load()
|
2023-04-07 14:59:07 +00:00
|
|
|
l := &log.Logger{}
|
|
|
|
c := config.GetConfig()
|
|
|
|
if c.LogOutput == "" {
|
|
|
|
c.LogOutput = "stderr"
|
2022-09-27 07:35:34 +00:00
|
|
|
}
|
2023-04-07 14:59:07 +00:00
|
|
|
var out io.Writer
|
|
|
|
switch c.LogOutput {
|
|
|
|
case "stdout":
|
|
|
|
out = os.Stdout
|
|
|
|
case "stderr":
|
|
|
|
out = os.Stderr
|
|
|
|
default:
|
|
|
|
file, err := os.OpenFile(c.LogOutput, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
out = file
|
2023-04-09 13:51:12 +00:00
|
|
|
logFile.Store(file)
|
|
|
|
}
|
|
|
|
if preFD != nil {
|
|
|
|
_ = preFD.Close()
|
2023-04-07 14:59:07 +00:00
|
|
|
}
|
|
|
|
logs.Store(l)
|
|
|
|
l.SetFlags(log.Ldate | log.Ltime)
|
|
|
|
l.SetOutput(out)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Errs(err error, depth int, desc string, args ...any) {
|
2023-04-06 13:13:02 +00:00
|
|
|
var pcs [1]uintptr
|
2023-04-07 14:59:07 +00:00
|
|
|
runtime.Callers(depth, pcs[:])
|
2023-04-06 13:13:02 +00:00
|
|
|
f := runtime.CallersFrames([]uintptr{pcs[0]})
|
|
|
|
ff, _ := f.Next()
|
|
|
|
s := strings.Builder{}
|
|
|
|
_, _ = fmt.Fprintf(&s, "%s:%d %s err:[%s]", ff.File, ff.Line, desc, err)
|
2022-09-27 07:35:34 +00:00
|
|
|
if len(args) > 0 {
|
|
|
|
s.WriteString(" args:")
|
|
|
|
for _, arg := range args {
|
2023-04-06 13:13:02 +00:00
|
|
|
_, _ = fmt.Fprintf(&s, "%v", arg)
|
2022-09-27 07:35:34 +00:00
|
|
|
}
|
|
|
|
}
|
2023-04-07 14:59:07 +00:00
|
|
|
logs.Load().Println(s.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
func Error(err error, desc string, args ...any) {
|
2023-04-10 14:28:16 +00:00
|
|
|
Errs(err, 3, desc, args...)
|
2023-04-07 14:59:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func IfError(err error, desc string, args ...any) {
|
|
|
|
if err == nil {
|
|
|
|
return
|
2022-09-27 07:35:34 +00:00
|
|
|
}
|
2023-04-07 14:59:07 +00:00
|
|
|
Errs(err, 3, desc, args...)
|
2022-09-27 07:35:34 +00:00
|
|
|
}
|