MarketingSystemDataTool/server/internal/logging/logging.go

40 lines
846 B
Go

package logging
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"time"
)
func Init(dir string) error {
if dir == "" {
dir = "log"
}
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
name := fmt.Sprintf("server-%s.log", time.Now().Format("20060102"))
p := filepath.Join(dir, name)
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
mw := io.MultiWriter(os.Stdout, f)
log.SetOutput(mw)
log.SetFlags(0)
return nil
}
func JSON(level string, fields map[string]interface{}) {
m := map[string]interface{}{"level": level, "ts": time.Now().Format(time.RFC3339)}
for k, v := range fields {
m[k] = v
}
b, _ := json.Marshal(m)
log.Println(string(b))
}