github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/log/transfer.go (about) 1 package log 2 3 import ( 4 "fmt" 5 "os" 6 "regexp" 7 "strconv" 8 "strings" 9 10 "github.com/sereiner/library/jsons" 11 12 "github.com/sereiner/library/net" 13 ) 14 15 var ip string 16 17 func init() { 18 ip = net.GetLocalIPAddress() 19 } 20 func transform(tpl string, event *LogEvent) (result string) { 21 word, _ := regexp.Compile(`%\w+`) 22 ecode := strings.Contains(tpl, "\"") 23 //@变量, 将数据放入params中 24 result = word.ReplaceAllStringFunc(tpl, func(s string) string { 25 key := s[1:] 26 switch key { 27 case "session": 28 return event.Session 29 case "date": 30 return event.Now.Format("20060102") 31 case "datetime": 32 return event.Now.Format("2006/01/02 15:04:05") 33 case "yy": 34 return event.Now.Format("2006") 35 case "mm": 36 return event.Now.Format("01") 37 case "dd": 38 return event.Now.Format("02") 39 case "hh": 40 return event.Now.Format("15") 41 case "mi": 42 return event.Now.Format("04") 43 case "ss": 44 return event.Now.Format("05") 45 case "ms": 46 return strconv.Itoa(event.Now.Nanosecond() / 1e3) 47 case "level": 48 return strings.ToLower(event.Level) 49 case "l": 50 return strings.ToLower(event.Level)[:1] 51 case "name": 52 return event.Name 53 case "pid": 54 return fmt.Sprintf("%d", os.Getpid()) 55 case "n": 56 return "\n" 57 case "caller": 58 return getCaller(8) 59 case "content": 60 if ecode { 61 return jsons.Escape(strings.Replace(event.Content, "\"", "'", -1)) 62 } 63 return event.Content 64 case "index": 65 return fmt.Sprintf("%d", event.Index) 66 case "ip": 67 return ip 68 default: 69 v, ok := event.Tags[key] 70 if ok { 71 return v 72 } 73 return "" 74 } 75 }) 76 return 77 }