github.com/astaxie/beego@v1.12.3/logs/accesslog.go (about)

     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  
    15  package logs
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  	"fmt"
    21  	"strings"
    22  	"time"
    23  )
    24  
    25  const (
    26  	apacheFormatPattern = "%s - - [%s] \"%s %d %d\" %f %s %s"
    27  	apacheFormat        = "APACHE_FORMAT"
    28  	jsonFormat          = "JSON_FORMAT"
    29  )
    30  
    31  // AccessLogRecord struct for holding access log data.
    32  type AccessLogRecord struct {
    33  	RemoteAddr     string        `json:"remote_addr"`
    34  	RequestTime    time.Time     `json:"request_time"`
    35  	RequestMethod  string        `json:"request_method"`
    36  	Request        string        `json:"request"`
    37  	ServerProtocol string        `json:"server_protocol"`
    38  	Host           string        `json:"host"`
    39  	Status         int           `json:"status"`
    40  	BodyBytesSent  int64         `json:"body_bytes_sent"`
    41  	ElapsedTime    time.Duration `json:"elapsed_time"`
    42  	HTTPReferrer   string        `json:"http_referrer"`
    43  	HTTPUserAgent  string        `json:"http_user_agent"`
    44  	RemoteUser     string        `json:"remote_user"`
    45  }
    46  
    47  func (r *AccessLogRecord) json() ([]byte, error) {
    48  	buffer := &bytes.Buffer{}
    49  	encoder := json.NewEncoder(buffer)
    50  	disableEscapeHTML(encoder)
    51  
    52  	err := encoder.Encode(r)
    53  	return buffer.Bytes(), err
    54  }
    55  
    56  func disableEscapeHTML(i interface{}) {
    57  	if e, ok := i.(interface {
    58  		SetEscapeHTML(bool)
    59  	}); ok {
    60  		e.SetEscapeHTML(false)
    61  	}
    62  }
    63  
    64  // AccessLog - Format and print access log.
    65  func AccessLog(r *AccessLogRecord, format string) {
    66  	var msg string
    67  	switch format {
    68  	case apacheFormat:
    69  		timeFormatted := r.RequestTime.Format("02/Jan/2006 03:04:05")
    70  		msg = fmt.Sprintf(apacheFormatPattern, r.RemoteAddr, timeFormatted, r.Request, r.Status, r.BodyBytesSent,
    71  			r.ElapsedTime.Seconds(), r.HTTPReferrer, r.HTTPUserAgent)
    72  	case jsonFormat:
    73  		fallthrough
    74  	default:
    75  		jsonData, err := r.json()
    76  		if err != nil {
    77  			msg = fmt.Sprintf(`{"Error": "%s"}`, err)
    78  		} else {
    79  			msg = string(jsonData)
    80  		}
    81  	}
    82  	beeLogger.writeMsg(levelLoggerImpl, strings.TrimSpace(msg))
    83  }