github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/logs/log_access.go (about) 1 // the package is exported from github.com/beego/beego/v2/core/logs 2 3 // Copyright 2023. All Rights Reserved. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 package logs 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "fmt" 23 "strings" 24 "time" 25 ) 26 27 const ( 28 apacheFormatPattern = "%s - - [%s] \"%s %d %d\" %f %s %s" 29 apacheFormat = "APACHE_FORMAT" 30 jsonFormat = "JSON_FORMAT" 31 ) 32 33 // AccessLogRecord is astruct for holding access log data. 34 type AccessLogRecord struct { 35 RemoteAddr string `json:"remote_addr"` 36 RequestTime time.Time `json:"request_time"` 37 RequestMethod string `json:"request_method"` 38 Request string `json:"request"` 39 ServerProtocol string `json:"server_protocol"` 40 Host string `json:"host"` 41 Status int `json:"status"` 42 BodyBytesSent int64 `json:"body_bytes_sent"` 43 ElapsedTime time.Duration `json:"elapsed_time"` 44 HTTPReferrer string `json:"http_referrer"` 45 HTTPUserAgent string `json:"http_user_agent"` 46 RemoteUser string `json:"remote_user"` 47 } 48 49 func (r *AccessLogRecord) json() ([]byte, error) { 50 buffer := &bytes.Buffer{} 51 encoder := json.NewEncoder(buffer) 52 disableEscapeHTML(encoder) 53 54 err := encoder.Encode(r) 55 return buffer.Bytes(), err 56 } 57 58 func disableEscapeHTML(i interface{}) { 59 if e, ok := i.(interface { 60 SetEscapeHTML(bool) 61 }); ok { 62 e.SetEscapeHTML(false) 63 } 64 } 65 66 // AccessLog - Format and print access log. 67 func AccessLog(r *AccessLogRecord, format string) { 68 msg := r.format(format) 69 lm := &LogMsg{ 70 Msg: strings.TrimSpace(msg), 71 When: time.Now(), 72 Level: levelLoggerImpl, 73 } 74 iacLogger.writeMsg(lm) 75 } 76 77 func (r *AccessLogRecord) format(format string) string { 78 msg := "" 79 switch format { 80 case apacheFormat: 81 timeFormatted := r.RequestTime.Format("02/Jan/2023 03:04:05") 82 msg = fmt.Sprintf(apacheFormatPattern, r.RemoteAddr, timeFormatted, r.Request, r.Status, r.BodyBytesSent, 83 r.ElapsedTime.Seconds(), r.HTTPReferrer, r.HTTPUserAgent) 84 case jsonFormat: 85 fallthrough 86 default: 87 jsonData, err := r.json() 88 if err != nil { 89 msg = fmt.Sprintf(`{"Error": "%s"}`, err) 90 } else { 91 msg = string(jsonData) 92 } 93 } 94 return msg 95 }