github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_server_log.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package ghttp 8 9 import ( 10 "fmt" 11 12 "github.com/wangyougui/gf/v2/errors/gerror" 13 "github.com/wangyougui/gf/v2/internal/instance" 14 "github.com/wangyougui/gf/v2/os/glog" 15 "github.com/wangyougui/gf/v2/text/gstr" 16 ) 17 18 // handleAccessLog handles the access logging for server. 19 func (s *Server) handleAccessLog(r *Request) { 20 if !s.IsAccessLogEnabled() { 21 return 22 } 23 var ( 24 scheme = "http" 25 proto = r.Header.Get("X-Forwarded-Proto") 26 loggerInstanceKey = fmt.Sprintf(`Acccess Logger Of Server:%s`, s.instance) 27 ) 28 29 if r.TLS != nil || gstr.Equal(proto, "https") { 30 scheme = "https" 31 } 32 content := fmt.Sprintf( 33 `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`, 34 r.Response.Status, r.Method, scheme, r.Host, r.URL.String(), r.Proto, 35 float64(r.LeaveTime-r.EnterTime)/1000, 36 r.GetClientIp(), r.Referer(), r.UserAgent(), 37 ) 38 logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() interface{} { 39 l := s.Logger().Clone() 40 l.SetFile(s.config.AccessLogPattern) 41 l.SetStdoutPrint(s.config.LogStdout) 42 l.SetLevelPrint(false) 43 return l 44 }).(*glog.Logger) 45 logger.Print(r.Context(), content) 46 } 47 48 // handleErrorLog handles the error logging for server. 49 func (s *Server) handleErrorLog(err error, r *Request) { 50 // It does nothing if error logging is custom disabled. 51 if !s.IsErrorLogEnabled() { 52 return 53 } 54 var ( 55 code = gerror.Code(err) 56 scheme = "http" 57 codeDetail = code.Detail() 58 proto = r.Header.Get("X-Forwarded-Proto") 59 loggerInstanceKey = fmt.Sprintf(`Error Logger Of Server:%s`, s.instance) 60 codeDetailStr string 61 ) 62 if r.TLS != nil || gstr.Equal(proto, "https") { 63 scheme = "https" 64 } 65 if codeDetail != nil { 66 codeDetailStr = gstr.Replace(fmt.Sprintf(`%+v`, codeDetail), "\n", " ") 67 } 68 content := fmt.Sprintf( 69 `%d "%s %s %s %s %s" %.3f, %s, "%s", "%s", %d, "%s", "%+v"`, 70 r.Response.Status, r.Method, scheme, r.Host, r.URL.String(), r.Proto, 71 float64(r.LeaveTime-r.EnterTime)/1000, 72 r.GetClientIp(), r.Referer(), r.UserAgent(), 73 code.Code(), code.Message(), codeDetailStr, 74 ) 75 if s.config.ErrorStack { 76 if stack := gerror.Stack(err); stack != "" { 77 content += "\nStack:\n" + stack 78 } else { 79 content += ", " + err.Error() 80 } 81 } else { 82 content += ", " + err.Error() 83 } 84 logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() interface{} { 85 l := s.Logger().Clone() 86 l.SetStack(false) 87 l.SetFile(s.config.ErrorLogPattern) 88 l.SetStdoutPrint(s.config.LogStdout) 89 l.SetLevelPrint(false) 90 return l 91 }).(*glog.Logger) 92 logger.Error(r.Context(), content) 93 }