transfer_middleware/until/sysLog/log.go

89 lines
2.1 KiB
Go
Raw Normal View History

2024-06-12 13:46:14 +08:00
package sysLog
2024-06-07 11:11:04 +08:00
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"os"
2024-06-12 13:46:14 +08:00
"path/filepath"
2024-06-07 11:11:04 +08:00
"time"
)
func ErrLog(ctx context.Context, errContent ...any) {
path, _ := errLogFile()
// 创建一个文件对象
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
logx.Error(err)
return
}
defer file.Close()
// 创建一个日志写入器,将日志写入文件
writer := logx.NewWriter(file)
// 使用该写入器记录日志
logx.SetWriter(writer)
logx.WithContext(ctx).WithCallerSkip(2).Errorf("errlog:", errContent)
}
2024-06-12 13:46:14 +08:00
func LogMq(ctx context.Context, content ...any) {
path, _ := logMqPath()
// 创建一个文件对象
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
logx.Error(err)
return
}
defer file.Close()
// 创建一个日志写入器,将日志写入文件
writer := logx.NewWriter(file)
// 使用该写入器记录日志
logx.SetWriter(writer)
logx.WithContext(ctx).WithCallerSkip(2).Info("mq:", content)
}
func logMqPath() (string, error) {
logPath, err := runtimePath()
if err != nil {
return "", err
}
path := fmt.Sprintf("%s/%s", logPath, "mq")
err = CheckDir(path)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", path, time.Now().Format(time.DateOnly)), nil
}
2024-06-07 11:11:04 +08:00
func errLogFile() (string, error) {
logPath, err := runtimePath()
if err != nil {
return "", err
}
path := fmt.Sprintf("%s/%s", logPath, "err")
err = CheckDir(path)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", path, time.Now().Format(time.DateOnly)), nil
}
func runtimePath() (string, error) {
path, err := os.Getwd()
2024-06-12 13:46:14 +08:00
return fmt.Sprintf("%s/%s/", filepath.Dir(filepath.Dir(path)), "runtime"), err
2024-06-07 11:11:04 +08:00
}
func CheckDir(path string) error {
// 判断目录是否存在
if _, err := os.Stat(path); os.IsNotExist(err) {
// 如果目录不存在,则创建它
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
} else if err != nil {
// 如果Stat返回了其他错误比如权限问题
return err
}
return nil
}