github.com/TeaOSLab/EdgeNode@v1.3.8/internal/nodes/http_request_log.go (about)

     1  package nodes
     2  
     3  import (
     4  	"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
     5  	"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
     6  	"strings"
     7  	"time"
     8  )
     9  
    10  const (
    11  	// AccessLogMaxRequestBodySize 访问日志存储的请求内容最大尺寸 TODO 此值应该可以在访问日志页设置
    12  	AccessLogMaxRequestBodySize = 2 << 20
    13  )
    14  
    15  // 日志
    16  func (this *HTTPRequest) log() {
    17  	// 检查全局配置
    18  	if this.nodeConfig != nil && this.nodeConfig.GlobalServerConfig != nil && !this.nodeConfig.GlobalServerConfig.HTTPAccessLog.IsOn {
    19  		return
    20  	}
    21  
    22  	var ref *serverconfigs.HTTPAccessLogRef
    23  	if !this.forceLog {
    24  		if this.disableLog {
    25  			return
    26  		}
    27  
    28  		// 计算请求时间
    29  		this.requestCost = time.Since(this.requestFromTime).Seconds()
    30  
    31  		ref = this.web.AccessLogRef
    32  		if ref == nil {
    33  			ref = serverconfigs.DefaultHTTPAccessLogRef
    34  		}
    35  		if !ref.IsOn {
    36  			return
    37  		}
    38  
    39  		if !ref.Match(this.writer.StatusCode()) {
    40  			return
    41  		}
    42  
    43  		if ref.FirewallOnly && this.firewallPolicyId == 0 {
    44  			return
    45  		}
    46  
    47  		// 是否记录499
    48  		if !ref.EnableClientClosed && this.writer.StatusCode() == 499 {
    49  			return
    50  		}
    51  	}
    52  
    53  	var addr = this.RawReq.RemoteAddr
    54  	var index = strings.LastIndex(addr, ":")
    55  	if index > 0 {
    56  		addr = addr[:index]
    57  	}
    58  
    59  	var serverGlobalConfig = this.nodeConfig.GlobalServerConfig
    60  
    61  	// 请求Cookie
    62  	var cookies = map[string]string{}
    63  	var enableCookies = false
    64  	if serverGlobalConfig == nil || serverGlobalConfig.HTTPAccessLog.EnableCookies {
    65  		enableCookies = true
    66  		if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldCookie) {
    67  			for _, cookie := range this.RawReq.Cookies() {
    68  				cookies[cookie.Name] = cookie.Value
    69  			}
    70  		}
    71  	}
    72  
    73  	// 请求Header
    74  	var pbReqHeader = map[string]*pb.Strings{}
    75  	if serverGlobalConfig == nil || serverGlobalConfig.HTTPAccessLog.EnableRequestHeaders {
    76  		if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldHeader) {
    77  			// 是否只记录通用Header
    78  			var commonHeadersOnly = serverGlobalConfig != nil && serverGlobalConfig.HTTPAccessLog.CommonRequestHeadersOnly
    79  
    80  			for k, v := range this.RawReq.Header {
    81  				if commonHeadersOnly && !serverconfigs.IsCommonRequestHeader(k) {
    82  					continue
    83  				}
    84  				if !enableCookies && k == "Cookie" {
    85  					continue
    86  				}
    87  				pbReqHeader[k] = &pb.Strings{Values: v}
    88  			}
    89  		}
    90  	}
    91  
    92  	// 响应Header
    93  	var pbResHeader = map[string]*pb.Strings{}
    94  	if serverGlobalConfig == nil || serverGlobalConfig.HTTPAccessLog.EnableResponseHeaders {
    95  		if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldSentHeader) {
    96  			for k, v := range this.writer.Header() {
    97  				pbResHeader[k] = &pb.Strings{Values: v}
    98  			}
    99  		}
   100  	}
   101  
   102  	// 参数列表
   103  	var queryString = ""
   104  	if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldArg) {
   105  		queryString = this.requestQueryString()
   106  	}
   107  
   108  	// 浏览器
   109  	var userAgent = ""
   110  	if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldUserAgent) || ref.ContainsField(serverconfigs.HTTPAccessLogFieldExtend) {
   111  		userAgent = this.RawReq.UserAgent()
   112  	}
   113  
   114  	// 请求来源
   115  	var referer = ""
   116  	if ref == nil || ref.ContainsField(serverconfigs.HTTPAccessLogFieldReferer) {
   117  		referer = this.RawReq.Referer()
   118  	}
   119  
   120  	var accessLog = &pb.HTTPAccessLog{
   121  		RequestId:       this.requestId,
   122  		NodeId:          this.nodeConfig.Id,
   123  		ServerId:        this.ReqServer.Id,
   124  		RemoteAddr:      this.requestRemoteAddr(true),
   125  		RawRemoteAddr:   addr,
   126  		RemotePort:      int32(this.requestRemotePort()),
   127  		RemoteUser:      this.requestRemoteUser(),
   128  		RequestURI:      this.rawURI,
   129  		RequestPath:     this.Path(),
   130  		RequestLength:   this.requestLength(),
   131  		RequestTime:     this.requestCost,
   132  		RequestMethod:   this.RawReq.Method,
   133  		RequestFilename: this.requestFilename(),
   134  		Scheme:          this.requestScheme(),
   135  		Proto:           this.RawReq.Proto,
   136  		BytesSent:       this.writer.SentBodyBytes(), // TODO 加上Header Size
   137  		BodyBytesSent:   this.writer.SentBodyBytes(),
   138  		Status:          int32(this.writer.StatusCode()),
   139  		StatusMessage:   "",
   140  		TimeISO8601:     this.requestFromTime.Format("2006-01-02T15:04:05.000Z07:00"),
   141  		TimeLocal:       this.requestFromTime.Format("2/Jan/2006:15:04:05 -0700"),
   142  		Msec:            float64(this.requestFromTime.Unix()) + float64(this.requestFromTime.Nanosecond())/1000000000,
   143  		Timestamp:       this.requestFromTime.Unix(),
   144  		Host:            this.ReqHost,
   145  		Referer:         referer,
   146  		UserAgent:       userAgent,
   147  		Request:         this.requestString(),
   148  		ContentType:     this.writer.Header().Get("Content-Type"),
   149  		Cookie:          cookies,
   150  		Args:            queryString,
   151  		QueryString:     queryString,
   152  		Header:          pbReqHeader,
   153  		ServerName:      this.ServerName,
   154  		ServerPort:      int32(this.requestServerPort()),
   155  		ServerProtocol:  this.RawReq.Proto,
   156  		SentHeader:      pbResHeader,
   157  		Errors:          this.errors,
   158  		Hostname:        HOSTNAME,
   159  
   160  		FirewallPolicyId:    this.firewallPolicyId,
   161  		FirewallRuleGroupId: this.firewallRuleGroupId,
   162  		FirewallRuleSetId:   this.firewallRuleSetId,
   163  		FirewallRuleId:      this.firewallRuleId,
   164  		FirewallActions:     this.firewallActions,
   165  		Tags:                this.tags,
   166  
   167  		Attrs: this.logAttrs,
   168  	}
   169  
   170  	if this.origin != nil {
   171  		accessLog.OriginId = this.origin.Id
   172  		accessLog.OriginAddress = this.originAddr
   173  		accessLog.OriginStatus = this.originStatus
   174  	}
   175  
   176  	// 请求Body
   177  	if (ref != nil && ref.ContainsField(serverconfigs.HTTPAccessLogFieldRequestBody)) || this.wafHasRequestBody {
   178  		accessLog.RequestBody = this.requestBodyData
   179  
   180  		if len(accessLog.RequestBody) > AccessLogMaxRequestBodySize {
   181  			accessLog.RequestBody = accessLog.RequestBody[:AccessLogMaxRequestBodySize]
   182  		}
   183  	}
   184  
   185  	// TODO 记录匹配的 locationId和rewriteId,非必要需求
   186  
   187  	sharedHTTPAccessLogQueue.Push(accessLog)
   188  }