全面替换log为zap

This commit is contained in:
2024-11-08 18:42:13 +08:00
parent 3da1fe761e
commit edb8d30605
17 changed files with 269 additions and 55 deletions

View File

@@ -4,10 +4,9 @@ Copyright © 2024 慕枫Go <mapleafgo@163.com>
package cmd
import (
"fmt"
"game-driver/config"
"game-driver/internal"
"log"
"game-driver/pkg/logger"
"os"
"github.com/spf13/cobra"
@@ -57,11 +56,11 @@ func initConfig() {
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
logger.Infof("Using config file: %s", viper.ConfigFileUsed())
}
err := viper.Unmarshal(&config.C)
if err != nil {
log.Panicln("unmarshal config failed: ", err)
logger.Panicln("unmarshal config failed: ", err)
}
}

1
go.mod
View File

@@ -40,6 +40,7 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/goleak v1.3.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sys v0.26.0 // indirect

2
go.sum
View File

@@ -128,6 +128,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=

View File

@@ -4,9 +4,9 @@ import (
"game-driver/internal/schema"
"game-driver/leaf"
"game-driver/pkg/audio"
"game-driver/pkg/logger"
"game-driver/pkg/utils"
"github.com/gopxl/beep/v2/speaker"
"log"
"sync"
)
@@ -33,7 +33,7 @@ func PlayBgm() leaf.HandlerFunc {
ctrl, closer := audio.PlayBgmMP3(bgm)
defer closer()
if ctrl == nil {
log.Println("播放背景音乐失败")
logger.Infoln("播放背景音乐失败")
return
}

View File

@@ -4,7 +4,7 @@ import (
"encoding/json"
"game-driver/internal/schema"
"game-driver/leaf"
"log"
"game-driver/pkg/logger"
)
type JSONKey string
@@ -17,7 +17,7 @@ func PayloadJSON[T schema.JsonModel]() leaf.HandlerFunc {
pm := new(T)
err := json.Unmarshal(c.Payload, pm)
if err != nil {
log.Panicf("报文解析错误: %v\n", err)
logger.Panicf("报文解析错误: %v\n", err)
}
leaf.WithValue[*T](c, PayloadJSONKey, pm)
c.Next()

View File

@@ -2,13 +2,13 @@ package middleware
import (
"game-driver/leaf"
"log"
"game-driver/pkg/logger"
)
func RunLog() leaf.HandlerFunc {
return func(c *leaf.Context) {
log.Printf("收到消息, topic: %s, payload: %s", c.Topic, c.Payload)
defer log.Println("执行结束")
logger.Infof("收到消息, topic: %s, payload: %s", c.Topic, c.Payload)
defer logger.Infof("执行结束")
c.Next()
}

View File

@@ -3,7 +3,7 @@ package routes
import (
"game-driver/internal/common"
"game-driver/leaf"
"log"
"game-driver/pkg/logger"
)
func Command(d *common.Device) leaf.HandlerFunc {
@@ -17,7 +17,7 @@ func Command(d *common.Device) leaf.HandlerFunc {
case "status":
d.PublishStatus()
default:
log.Printf("接收到无效指令: %s\n", cmd)
logger.Infof("接收到无效指令: %s\n", cmd)
}
}
}

View File

@@ -5,12 +5,12 @@ import (
"game-driver/internal/schema"
"game-driver/leaf"
"game-driver/pkg/audio"
"game-driver/pkg/logger"
"game-driver/pkg/relay"
"game-driver/pkg/tts"
"game-driver/pkg/utils"
"game-driver/pkg/video"
"github.com/gopxl/beep/v2/speaker"
"log"
"sync"
"time"
)
@@ -34,7 +34,7 @@ func WaitAction(c *leaf.Context) {
payload := leaf.Value[*schema.WaitModel](c, middleware.PayloadJSONKey)
if payload.Start != 0 && payload.End != 0 && time.Unix(payload.Start, 0).After(time.Unix(payload.End, 0)) {
log.Println("开始时间大于结束时间")
logger.Infoln("开始时间大于结束时间")
return
}
@@ -81,7 +81,7 @@ func WaitAction(c *leaf.Context) {
}()
case schema.WaitWeb:
default:
log.Printf("不支持的类型: %d\n", item.Type)
logger.Infof("不支持的类型: %d\n", item.Type)
}
}
}
@@ -89,7 +89,7 @@ func WaitAction(c *leaf.Context) {
func audioAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel) {
if item.Start != 0 && time.Unix(item.Start, 0).Before(time.Unix(root.Start, 0)) {
log.Println("开始时间小于根任务开始时间")
logger.Infoln("开始时间小于根任务开始时间")
return
}
@@ -102,13 +102,13 @@ func audioAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeMod
case <-c.Done():
case <-timerAction(item.Start):
{
log.Println("开始执行后台任务")
logger.Infoln("开始执行后台任务")
data := utils.LinkAudio(item.Data)
ctrl, closer := audio.PlayBgmMP3(data)
defer closer()
if ctrl == nil {
log.Println("播放背景音乐失败")
logger.Infoln("播放背景音乐失败")
return
}
@@ -126,7 +126,7 @@ func audioAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeMod
func ttsAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel) {
if item.Start != 0 && time.Unix(item.Start, 0).Before(time.Unix(root.Start, 0)) {
log.Println("开始时间小于根任务开始时间")
logger.Infoln("开始时间小于根任务开始时间")
return
}
@@ -137,7 +137,7 @@ func ttsAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel
reader, err := tts.DefaultTTS.Get(item.Data)
if err != nil {
log.Println("语音合成异常: ", err)
logger.Infoln("语音合成异常: ", err)
return
}
@@ -159,7 +159,7 @@ func ttsAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel
func relayAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel) {
if item.Start != 0 && time.Unix(item.Start, 0).Before(time.Unix(root.Start, 0)) {
log.Println("开始时间小于根任务开始时间")
logger.Infoln("开始时间小于根任务开始时间")
return
}
@@ -170,7 +170,7 @@ func relayAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeMod
device, err := relay.New(item.Data, nil)
if err != nil {
log.Println("继电器初始化异常: ", err)
logger.Infoln("继电器初始化异常: ", err)
return
}
defer device.Close()
@@ -188,7 +188,7 @@ func relayAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeMod
func videoAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeModel) {
if item.Start != 0 && time.Unix(item.Start, 0).Before(time.Unix(root.Start, 0)) {
log.Println("开始时间小于根任务开始时间")
logger.Infoln("开始时间小于根任务开始时间")
return
}
@@ -207,7 +207,7 @@ func videoAction(c *leaf.Context, item schema.WaitItemModel, root schema.TimeMod
for {
err := video.Play(c, utils.LinkVideo(item.Data))
if err != nil {
log.Panicln("视频播放异常: ", err)
logger.Panicln("视频播放异常: ", err)
}
select {
case <-c.Done():

View File

@@ -9,11 +9,12 @@ import (
"game-driver/internal/routes"
"game-driver/internal/schema"
"game-driver/leaf"
"game-driver/pkg/logger"
"game-driver/pkg/tts"
"game-driver/pkg/utils"
"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
"log"
"go.uber.org/zap"
"net/url"
"os"
"os/signal"
@@ -24,12 +25,12 @@ import (
func buildMqtt(c config.MqttConfig, r *leaf.Engine, subTopics ...string) autopaho.ClientConfig {
u, err := url.Parse(c.Url)
if err != nil {
log.Panicln("mqtt url parse error: ", err)
logger.Panicln("mqtt url parse error: ", err)
}
subscriptions := make([]paho.SubscribeOptions, 0)
for _, topic := range subTopics {
log.Println("订阅主题: ", topic)
logger.Infoln("订阅主题: ", topic)
subscriptions = append(subscriptions, paho.SubscribeOptions{Topic: topic, QoS: 0})
}
@@ -39,17 +40,17 @@ func buildMqtt(c config.MqttConfig, r *leaf.Engine, subTopics ...string) autopah
CleanStartOnInitialConnection: false,
SessionExpiryInterval: 60,
OnConnectionUp: func(cm *autopaho.ConnectionManager, _ *paho.Connack) {
log.Println("MQTT 连接成功")
logger.Infoln("MQTT 连接成功")
if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{
Subscriptions: subscriptions,
}); err != nil {
log.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
logger.Infof("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
return
}
log.Println("订阅完成")
logger.Infoln("订阅完成")
},
OnConnectError: func(err error) {
log.Printf("MQTT 连接异常: %s\n", err)
logger.Infof("MQTT 连接异常: %s\n", err)
},
ClientConfig: paho.ClientConfig{
ClientID: "TestSubscriber",
@@ -81,9 +82,11 @@ func Run() {
defer cancel()
router := leaf.Default(ctx)
log := zap.NewStdLog(logger.DefaultLogger.Zap())
router.SetDebugLogger(log)
router.DefaultHandler(func(c *leaf.Context) {
log.Printf("未处理消息 topic: %s\n payload: %s\n", c.Topic, c.Payload)
logger.Infof("未处理消息topic: %s\n payload: %s\n", c.Topic, c.Payload)
})
// 构建 MQTT 连接
@@ -92,7 +95,7 @@ func Run() {
// 连接 MQTT
cm, err := autopaho.NewConnection(ctx, mqttBuild)
if err != nil {
log.Panicln("连接 MQTT 异常: ", err)
logger.Panicln("连接 MQTT 异常: ", err)
}
// 构建语音合成对象
@@ -100,10 +103,10 @@ func Run() {
// 构建继电器对象
//r, err := relay.New(config.C.Relay, func(msg string) {
// log.Println("串口返回: ", msg)
// logger.Infoln("串口返回: ", msg)
//})
//if err != nil {
// log.Panicln("串口连接异常: ", err)
// logger.Panicln("串口连接异常: ", err)
//}
//defer r.Close()

View File

@@ -5,8 +5,8 @@
package leaf
import (
"game-driver/pkg/logger"
"io"
"log"
)
// RecoveryFunc defines the function passable to CustomRecovery.
@@ -35,7 +35,7 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
return func(c *Context) {
defer func() {
if err := recover(); err != nil {
log.Println("执行出错: ", err)
logger.Infoln("执行出错: ", err)
handle(c, err)
}
}()

View File

@@ -1,11 +1,11 @@
package audio
import (
"game-driver/pkg/logger"
"github.com/gopxl/beep/v2"
"github.com/gopxl/beep/v2/mp3"
"github.com/gopxl/beep/v2/speaker"
"io"
"log"
)
func PlayBgmMP3(r io.ReadCloser, opts ...beep.LoopOption) (*beep.Ctrl, func() error) {
@@ -16,7 +16,7 @@ func PlayBgmMP3(r io.ReadCloser, opts ...beep.LoopOption) (*beep.Ctrl, func() er
loop2, err := beep.Loop2(streamer, opts...)
if err != nil {
log.Println("循环播放异常: ", err)
logger.Infoln("循环播放异常: ", err)
return nil, streamer.Close
}

View File

@@ -2,12 +2,12 @@ package audio
import (
"context"
"game-driver/pkg/logger"
"github.com/gopxl/beep/v2"
"github.com/gopxl/beep/v2/mp3"
"github.com/gopxl/beep/v2/speaker"
"github.com/gopxl/beep/v2/wav"
"io"
"log"
"time"
)
@@ -18,7 +18,7 @@ func init() {
if err != nil {
panic("扬声器初始化异常: " + err.Error())
}
log.Println("扬声器初始化完成")
logger.Infoln("扬声器初始化完成")
}
func PlayWav(c context.Context, r io.Reader) {

208
pkg/logger/logger.go Normal file
View File

@@ -0,0 +1,208 @@
package logger
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Logger struct {
zl *zap.Logger
zs zap.SugaredLogger
}
func NewLogger() *Logger {
logger, _ := zap.NewDevelopment(zap.AddCallerSkip(1))
sugar := logger.Sugar()
return &Logger{
zl: logger,
zs: *sugar,
}
}
func (l *Logger) Zap() *zap.Logger {
return l.zl
}
var DefaultLogger = NewLogger()
// Debug logs the provided arguments at [DebugLevel].
// Spaces are added between arguments when neither is a string.
func Debug(args ...interface{}) {
DefaultLogger.zs.Log(zap.DebugLevel, args...)
}
// Info logs the provided arguments at [InfoLevel].
// Spaces are added between arguments when neither is a string.
func Info(args ...interface{}) {
DefaultLogger.zs.Log(zap.InfoLevel, args...)
}
// Warn logs the provided arguments at [WarnLevel].
// Spaces are added between arguments when neither is a string.
func Warn(args ...interface{}) {
DefaultLogger.zs.Log(zap.WarnLevel, args...)
}
// Error logs the provided arguments at [ErrorLevel].
// Spaces are added between arguments when neither is a string.
func Error(args ...interface{}) {
DefaultLogger.zs.Log(zap.ErrorLevel, args...)
}
// DPanic logs the provided arguments at [DPanicLevel].
// In development, the logger then panics. (See [DPanicLevel] for details.)
// Spaces are added between arguments when neither is a string.
func DPanic(args ...interface{}) {
DefaultLogger.zs.Log(zap.DPanicLevel, args...)
}
// Panic constructs a message with the provided arguments and panics.
// Spaces are added between arguments when neither is a string.
func Panic(args ...interface{}) {
DefaultLogger.zs.Log(zap.PanicLevel, args...)
}
// Fatal constructs a message with the provided arguments and calls os.Exit.
// Spaces are added between arguments when neither is a string.
func Fatal(args ...interface{}) {
DefaultLogger.zs.Log(zap.FatalLevel, args...)
}
// Logf formats the message according to the format specifier
// and logs it at provided level.
func Logf(lvl zapcore.Level, template string, args ...interface{}) {
DefaultLogger.zs.Logf(lvl, template, args...)
}
// Debugf formats the message according to the format specifier
// and logs it at [DebugLevel].
func Debugf(template string, args ...interface{}) {
DefaultLogger.zs.Debugf(template, args...)
}
// Infof formats the message according to the format specifier
// and logs it at [InfoLevel].
func Infof(template string, args ...interface{}) {
DefaultLogger.zs.Infof(template, args...)
}
// Warnf formats the message according to the format specifier
// and logs it at [WarnLevel].
func Warnf(template string, args ...interface{}) {
DefaultLogger.zs.Warnf(template, args...)
}
// Errorf formats the message according to the format specifier
// and logs it at [ErrorLevel].
func Errorf(template string, args ...interface{}) {
DefaultLogger.zs.Errorf(template, args...)
}
// DPanicf formats the message according to the format specifier
// and logs it at [DPanicLevel].
// In development, the logger then panics. (See [DPanicLevel] for details.)
func DPanicf(template string, args ...interface{}) {
DefaultLogger.zs.DPanicf(template, args...)
}
// Panicf formats the message according to the format specifier
// and panics.
func Panicf(template string, args ...interface{}) {
DefaultLogger.zs.Panicf(template, args...)
}
// Fatalf formats the message according to the format specifier
// and calls os.Exit.
func Fatalf(template string, args ...interface{}) {
DefaultLogger.zs.Fatalf(template, args...)
}
// Debugw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
//
// When debug-level logging is disabled, this is much faster than
//
// s.With(keysAndValues).Debug(msg)
func Debugw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Debugw(msg, keysAndValues...)
}
// Infow logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func Infow(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Infow(msg, keysAndValues...)
}
// Warnw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func Warnw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Warnw(msg, keysAndValues...)
}
// Errorw logs a message with some additional context. The variadic key-value
// pairs are treated as they are in With.
func Errorw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Errorw(msg, keysAndValues...)
}
// DPanicw logs a message with some additional context. In development, the
// logger then panics. (See DPanicLevel for details.) The variadic key-value
// pairs are treated as they are in With.
func DPanicw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.DPanicw(msg, keysAndValues...)
}
// Panicw logs a message with some additional context, then panics. The
// variadic key-value pairs are treated as they are in With.
func Panicw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Panicw(msg, keysAndValues...)
}
// Fatalw logs a message with some additional context, then calls os.Exit. The
// variadic key-value pairs are treated as they are in With.
func Fatalw(msg string, keysAndValues ...interface{}) {
DefaultLogger.zs.Fatalw(msg, keysAndValues...)
}
// Debugln logs a message at [DebugLevel].
// Spaces are always added between arguments.
func Debugln(args ...interface{}) {
DefaultLogger.zs.Debugln(args...)
}
// Infoln logs a message at [InfoLevel].
// Spaces are always added between arguments.
func Infoln(args ...interface{}) {
DefaultLogger.zs.Infoln(args...)
}
// Warnln logs a message at [WarnLevel].
// Spaces are always added between arguments.
func Warnln(args ...interface{}) {
DefaultLogger.zs.Warnln(args...)
}
// Errorln logs a message at [ErrorLevel].
// Spaces are always added between arguments.
func Errorln(args ...interface{}) {
DefaultLogger.zs.Errorln(args...)
}
// DPanicln logs a message at [DPanicLevel].
// In development, the logger then panics. (See [DPanicLevel] for details.)
// Spaces are always added between arguments.
func DPanicln(args ...interface{}) {
DefaultLogger.zs.DPanicln(args...)
}
// Panicln logs a message at [PanicLevel] and panics.
// Spaces are always added between arguments.
func Panicln(args ...interface{}) {
DefaultLogger.zs.Panicln(args...)
}
// Fatalln logs a message at [FatalLevel] and calls os.Exit.
// Spaces are always added between arguments.
func Fatalln(args ...interface{}) {
DefaultLogger.zs.Fatalln(args...)
}

View File

@@ -8,6 +8,7 @@ import (
"game-driver/leaf"
"game-driver/pkg/audio"
"game-driver/pkg/errorsx"
"game-driver/pkg/logger"
"io"
"log"
"time"
@@ -48,7 +49,7 @@ func (tts *AliTTS) Sound(text string) {
if err == nil && buf != nil {
audio.PlayWav(tts.ctx, buf)
} else {
log.Panicln("AliTTS 请求异常: ", err)
logger.Panicln("AliTTS 请求异常: ", err)
}
}

View File

@@ -2,8 +2,8 @@ package utils
import (
"bytes"
"game-driver/pkg/logger"
"io"
"log"
"net/http"
"net/url"
"os"
@@ -32,7 +32,7 @@ func open(u string) io.ReadCloser {
p, _ := strings.CutPrefix(u, "file://")
f, e := os.Open(p)
if e != nil {
log.Printf("音频文件 [%v] 打开错误: %v\n", u, e)
logger.Infof("音频文件 [%v] 打开错误: %v\n", u, e)
return nil
}
return f
@@ -41,7 +41,7 @@ func open(u string) io.ReadCloser {
func get(u string) io.ReadCloser {
resp, e := http.Get(u)
if e != nil {
log.Printf("音频文件 [%v] 下载失败: %v\n", u, e)
logger.Infof("音频文件 [%v] 下载失败: %v\n", u, e)
return nil
}
return resp.Body
@@ -54,14 +54,14 @@ func LinkAudio(link string) (bgm io.ReadCloser) {
}
u, err := url.Parse(link)
if err != nil {
log.Println("音频 URL 解析错误: ", err)
logger.Infoln("音频 URL 解析错误: ", err)
} else {
if u.Scheme == "file" {
bgm = open(link)
} else if u.Scheme == "http" || u.Scheme == "https" {
bgm = get(link)
} else {
log.Printf("不支持的音频文件协议: %v\n", u.String())
logger.Infof("不支持的音频文件协议: %v\n", u.String())
return
}
bgm = toSeeker(bgm)

View File

@@ -1,8 +1,8 @@
package utils
import (
"game-driver/pkg/logger"
"io"
"log"
"net/http"
"net/url"
"os"
@@ -17,7 +17,7 @@ func LinkVideo(link string) (local string) {
}
u, err := url.Parse(link)
if err != nil {
log.Println("音频 URL 解析错误: ", err)
logger.Infoln("音频 URL 解析错误: ", err)
} else {
if u.Scheme == "file" {
local, _ = strings.CutPrefix(link, "file://")
@@ -26,12 +26,12 @@ func LinkVideo(link string) (local string) {
tmpLocal := path.Join(os.TempDir(), path.Base(p))
err = Download(link, tmpLocal)
if err != nil {
log.Println("音频文件下载失败: ", err)
logger.Infoln("音频文件下载失败: ", err)
return
}
local = tmpLocal
} else {
log.Printf("不支持的视频链接协议: %v\n", u.String())
logger.Infof("不支持的视频链接协议: %v\n", u.String())
return
}
}

View File

@@ -3,15 +3,15 @@ package video
import (
"bufio"
"context"
"game-driver/pkg/logger"
"io"
"log"
"os/exec"
"sync"
)
func Play(ctx context.Context, file string) error {
if file == "" {
log.Println("video file is empty")
logger.Infoln("video file is empty")
return nil
}
cmd := exec.CommandContext(ctx, "ffplay", "-autoexit", "-fs", file)
@@ -39,7 +39,7 @@ func Play(ctx context.Context, file string) error {
}
break
}
log.Println(string(line))
logger.Infoln(string(line))
}
}
}()