github.com/gogf/gf@v1.16.9/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/gogf/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"fmt"
    11  	"github.com/gogf/gf/errors/gerror"
    12  )
    13  
    14  // handleAccessLog handles the access logging for server.
    15  func (s *Server) handleAccessLog(r *Request) {
    16  	if !s.IsAccessLogEnabled() {
    17  		return
    18  	}
    19  	scheme := "http"
    20  	if r.TLS != nil {
    21  		scheme = "https"
    22  	}
    23  	s.Logger().Ctx(r.Context()).File(s.config.AccessLogPattern).
    24  		Stdout(s.config.LogStdout).
    25  		Printf(
    26  			`%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
    27  			r.Response.Status,
    28  			r.Method, scheme, r.Host, r.URL.String(), r.Proto,
    29  			float64(r.LeaveTime-r.EnterTime)/1000,
    30  			r.GetClientIp(), r.Referer(), r.UserAgent(),
    31  		)
    32  }
    33  
    34  // handleErrorLog handles the error logging for server.
    35  func (s *Server) handleErrorLog(err error, r *Request) {
    36  	// It does nothing if error logging is custom disabled.
    37  	if !s.IsErrorLogEnabled() {
    38  		return
    39  	}
    40  
    41  	scheme := "http"
    42  	if r.TLS != nil {
    43  		scheme = "https"
    44  	}
    45  	content := fmt.Sprintf(
    46  		`%d "%s %s %s %s %s" %.3f, %s, "%s", "%s"`,
    47  		r.Response.Status, r.Method, scheme, r.Host, r.URL.String(), r.Proto,
    48  		float64(r.LeaveTime-r.EnterTime)/1000,
    49  		r.GetClientIp(), r.Referer(), r.UserAgent(),
    50  	)
    51  	if s.config.ErrorStack {
    52  		if stack := gerror.Stack(err); stack != "" {
    53  			content += "\nStack:\n" + stack
    54  		} else {
    55  			content += ", " + err.Error()
    56  		}
    57  	} else {
    58  		content += ", " + err.Error()
    59  	}
    60  	s.Logger().Ctx(r.Context()).
    61  		File(s.config.ErrorLogPattern).
    62  		Stdout(s.config.LogStdout).
    63  		Print(content)
    64  }