高热共公日志库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.4 KiB

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