github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/utils/accessLogUtils.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/siglens/siglens/pkg/common/dtypeutils"
    10  	log "github.com/sirupsen/logrus"
    11  )
    12  
    13  func DeferableAddAccessLogEntry(startTime time.Time, endTimeFunc func() time.Time, user string,
    14  	uri string, requestBody string, statusCodeFunc func() int, allowWebsocket bool, fileName string) {
    15  
    16  	data := dtypeutils.AccessLogData{
    17  		TimeStamp:   startTime.Format("2006-01-02 15:04:05"),
    18  		UserName:    user,
    19  		URI:         uri,
    20  		RequestBody: requestBody,
    21  		StatusCode:  statusCodeFunc(),
    22  		Duration:    endTimeFunc().Sub(startTime).Milliseconds(),
    23  	}
    24  	AddAccessLogEntry(data, allowWebsocket, fileName)
    25  }
    26  
    27  // Write to access.log in the following format
    28  // timeStamp <logged-in user> <request URI> <request body> <response status code> <elapsed time in ms>
    29  func AddAccessLogEntry(data dtypeutils.AccessLogData, allowWebsocket bool, fileName string) {
    30  	logFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    31  	if err != nil {
    32  		log.Errorf("Unable to write to access.log file, err=%v", err)
    33  	}
    34  	defer logFile.Close()
    35  
    36  	// Do not log websocket connections, unless explicitly allowed.
    37  	if data.StatusCode == 101 && !allowWebsocket {
    38  		return
    39  	}
    40  
    41  	// Do not log internal search requests for trace data
    42  	if (strings.TrimSpace(data.URI) == "http:///" || strings.TrimSpace(data.URI) == "https:///") && strings.Contains(data.RequestBody, "\"indexName\":\"traces\"") {
    43  		return
    44  	}
    45  
    46  	_, err = logFile.WriteString(fmt.Sprintf("%s %s %s %s %d %d\n",
    47  		data.TimeStamp,
    48  		data.UserName, // TODO : Add logged in user when user auth is implemented
    49  		data.URI,
    50  		data.RequestBody,
    51  		data.StatusCode,
    52  		data.Duration),
    53  	)
    54  	if err != nil {
    55  		log.Errorf("Unable to write to access.log file, err=%v", err)
    56  		return
    57  	}
    58  }