transfer_middleware/pkg/log/log.go

59 lines
1.3 KiB
Go
Executable File
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 pkg
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"os"
"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)
}
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()
return fmt.Sprintf("../%s/%s", 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
}