golang基於gin框架封裝的log日誌類
阿新 • • 發佈:2020-08-26
package util import ( "crypto/md5" "encoding/hex" "fmt" "os" "runtime" "strconv" "time" ) var strCGroupLogID string = "" func LogRecord(msg string, level string) (string, error) { ymd := time.Now().Format("2006-01-02") now := time.Now().Format("2006-01-02 15:04:05") fileName := GetAppPath() + "storage/" + level + "-" + ymd + ".log" logFile, logFileErr := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if logFileErr != nil { return "open log file fail", logFileErr } defer logFile.Close() _, file, line, _ := runtime.Caller(1)// log format = [時間] [使用者組日誌id] 日誌資訊 if strCGroupLogID == "" { strCGroupLogID = GenCGroupLogID() } logFile.WriteString("[" + now + "][" + strCGroupLogID + "]" + msg + ", FILE:" + file + ", LINE:" + strconv.Itoa(line) + "\r\n") return "log ok", nil } func GenCGroupLogID() string{ strGuid := GetGUID().Hex() strLocalIP := GetLocalIP() if strLocalIP == "" { strLocalIP = "127.0.0.1" } int64LocalIP := InetAtoN(strLocalIP) _ = strLocalIP strCGroupLogID = strconv.FormatInt(int64LocalIP, 10) + "-" + strGuid strCGroupLogID = Md5(strCGroupLogID) strCGroupLogID = getFormatUUID(strCGroupLogID) return strCGroupLogID } func SetCGroupLogID(logid string) string { strCGroupLogID = logid return "ok" } func GetCGroupLogID() string { return strCGroupLogID } //生成32位md5字串 func Md5(s string) string { h := md5.New() h.Write([]byte(s)) return hex.EncodeToString(h.Sum(nil)) } func getFormatUUID(s string) string { if len(s) != 32 { return s } return fmt.Sprintf("%s-%s-%s-%s-%s", s[0:8], s[8:12], s[12:16], s[16:20], s[20:32]) } func LogStack(err error) { var buf [4096]byte n := runtime.Stack(buf[:], false) LogRecord(err.Error() + "\r\n" + string(buf[:n]) + "\r\n", "panic") }
package api_controller import ( "fmt" "github.com/gin-gonic/gin" "net/http" "util" ) func Getsmscode(c *gin.Context) { defer func() { if r := recover(); r != nil { util.LogStack(r.(error)) //日誌呼叫 c.JSON(200, gin.H{"status": 500, "data": r, "msg": "網路異常,請稍後再試"}); return } }() var ( params string ) if params = c.DefaultPostForm("testkey", ""); params == "" { c.JSON(http.StatusOK, gin.H{"status": params, "data": "", "msg": "data不能為空"}) return } fmt.Println(params) }