2022-09-27 07:35:34 +00:00
|
|
|
package logs
|
|
|
|
|
|
|
|
import (
|
2023-04-06 13:13:02 +00:00
|
|
|
"fmt"
|
2023-05-04 12:36:17 +00:00
|
|
|
"github.com/fthvgb1/wp-go/app/pkg/config"
|
2023-04-07 14:59:07 +00:00
|
|
|
"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 {
|
|
|
|
c := config.GetConfig()
|
2024-06-12 14:38:49 +00:00
|
|
|
return SetLogger(c.LogOutput)
|
|
|
|
}
|
|
|
|
|
|
|
|
func SetLogger(loggerFile string) error {
|
|
|
|
if loggerFile == "" {
|
|
|
|
loggerFile = "stderr"
|
2022-09-27 07:35:34 +00:00
|
|
|
}
|
2024-06-12 14:38:49 +00:00
|
|
|
preFD := logFile.Load()
|
|
|
|
l := &log.Logger{}
|
2023-04-07 14:59:07 +00:00
|
|
|
var out io.Writer
|
2024-06-12 14:38:49 +00:00
|
|
|
switch loggerFile {
|
2023-04-07 14:59:07 +00:00
|
|
|
case "stdout":
|
|
|
|
out = os.Stdout
|
|
|
|
case "stderr":
|
|
|
|
out = os.Stderr
|
|
|
|
default:
|
2024-06-12 14:38:49 +00:00
|
|
|
file, err := os.OpenFile(loggerFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777)
|
2023-04-07 14:59:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
out = file
|
2023-04-09 13:51:12 +00:00
|
|
|
logFile.Store(file)
|
|
|
|
}
|
2023-04-11 05:42:14 +00:00
|
|
|
logs.Store(l)
|
2023-04-09 13:51:12 +00:00
|
|
|
if preFD != nil {
|
|
|
|
_ = preFD.Close()
|
2023-04-07 14:59:07 +00:00
|
|
|
}
|
|
|
|
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
|
|
|
}
|