transfer_middleware/until/sysLog/log.go

110 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package sysLog
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"os"
"path/filepath"
"time"
)
func ErrLog(ctx context.Context, errContent ...any) {
path, _ := errLogFile("err")
// 创建一个文件对象
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)
}
func LogSendMq(ctx context.Context, content ...any) {
path, _ := errLogFile("produce")
// 创建一个文件对象
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("sendMq:", content)
}
func ErrQueueLog(ctx context.Context, content ...any) {
path, _ := logQueuePath()
// 创建一个文件对象
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("queue:", content)
}
func logQueuePath() (string, error) {
logPath, err := runtimePathForQueue()
if err != nil {
return "", err
}
path := fmt.Sprintf("%s/%s", logPath, "queue")
err = CheckDir(path)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", path, time.Now().Format(time.DateOnly)), nil
}
func errLogFile(pathName string) (string, error) {
logPath, err := runtimePath()
if err != nil {
return "", err
}
path := fmt.Sprintf("%s/%s", logPath, pathName)
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()
return fmt.Sprintf("%s/%s/", filepath.Dir(filepath.Dir(path)), "runtime"), err
}
func runtimePathForQueue() (string, error) {
path, err := os.Getwd()
return fmt.Sprintf("%s/%s/", filepath.Dir(filepath.Dir(filepath.Dir(path))), "runtime"), err
}
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
}