├── img └── screenshot.png ├── context.go ├── go.mod ├── .circleci └── config.yml ├── example ├── net_http │ └── main.go └── chi │ └── main.go ├── go.sum ├── stackdriver_test.go ├── README.md ├── middleware.go ├── stackdriver.go └── LICENSE /img/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imos/stackdriver-request-context-log/master/img/screenshot.png -------------------------------------------------------------------------------- /context.go: -------------------------------------------------------------------------------- 1 | package stackdriverlog 2 | 3 | type contextKey struct{} 4 | 5 | var ( 6 | contextLoggerKey = &contextKey{} 7 | ) 8 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/yfuruyama/stackdriver-request-context-log 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/go-chi/chi v4.0.3+incompatible 7 | github.com/google/go-cmp v0.3.0 8 | go.opencensus.io v0.22.3 9 | ) 10 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | working_directory: /go/src/github.com/yfuruyama/stackdriver-request-context-log 5 | docker: 6 | - image: circleci/golang:1.13 7 | environment: 8 | GO111MODULE: "on" 9 | steps: 10 | - checkout 11 | - run: go mod download 12 | - run: go vet ./... 13 | - run: go test -v ./... 14 | -------------------------------------------------------------------------------- /example/net_http/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | 8 | log "github.com/yfuruyama/stackdriver-request-context-log" 9 | ) 10 | 11 | func main() { 12 | mux := http.NewServeMux() 13 | 14 | // Set request handler 15 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 16 | // Get request context logger 17 | logger := log.RequestContextLogger(r) 18 | 19 | // These logs are grouped with the request log 20 | logger.Debugf("Hi") 21 | logger.Infof("Hello") 22 | logger.Warnf("World") 23 | 24 | fmt.Fprintf(w, "OK\n") 25 | }) 26 | 27 | projectId := "my-gcp-project" 28 | 29 | // Make config for this library 30 | config := log.NewConfig(projectId) 31 | config.RequestLogOut = os.Stderr // request log to stderr 32 | config.ContextLogOut = os.Stdout // context log to stdout 33 | config.Severity = log.SeverityInfo // only over INFO logs are logged 34 | config.AdditionalData = log.AdditionalData{ // set additional fields for all logs 35 | "service": "foo", 36 | "version": 1.0, 37 | } 38 | 39 | // Set middleware for the request log to be automatically logged 40 | handler := log.RequestLogging(config)(mux) 41 | 42 | // Run server 43 | fmt.Println("Waiting requests on port 8080...") 44 | if err := http.ListenAndServe(":8080", handler); err != nil { 45 | panic(err) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /example/chi/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | 8 | "github.com/go-chi/chi" 9 | log "github.com/yfuruyama/stackdriver-request-context-log" 10 | ) 11 | 12 | func main() { 13 | router := chi.NewRouter() 14 | 15 | projectId := "my-gcp-project" 16 | 17 | // Make config for this library 18 | config := log.NewConfig(projectId) 19 | config.RequestLogOut = os.Stderr // request log to stderr 20 | config.ContextLogOut = os.Stdout // context log to stdout 21 | config.Severity = log.SeverityInfo // only over INFO logs are logged 22 | config.AdditionalData = log.AdditionalData{ // set additional fields for all logs 23 | "service": "foo", 24 | "version": 1.0, 25 | } 26 | 27 | // Set middleware for the request log to be automatically logged 28 | router.Use(log.RequestLogging(config)) 29 | 30 | // Set request handler 31 | router.Get("/", func(w http.ResponseWriter, r *http.Request) { 32 | // Get request context logger 33 | logger := log.RequestContextLogger(r) 34 | 35 | // These logs are grouped with the request log 36 | logger.Debugf("Hi") 37 | logger.Infof("Hello") 38 | logger.Warnf("World") 39 | 40 | fmt.Fprintf(w, "OK\n") 41 | }) 42 | 43 | // Run server 44 | fmt.Println("Waiting requests on port 8080...") 45 | if err := http.ListenAndServe(":8080", router); err != nil { 46 | panic(err) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/go-chi/chi v1.0.0 h1:s/kv1cTXfivYjdKJdyUzNGyAWZ/2t7duW1gKn5ivu+c= 6 | github.com/go-chi/chi v4.0.3+incompatible h1:gakN3pDJnzZN5jqFV2TEdF66rTfKeITyR8qu6ekICEY= 7 | github.com/go-chi/chi v4.0.3+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= 8 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 9 | github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= 10 | github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= 11 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 12 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 13 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 14 | github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= 15 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 17 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 18 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 19 | go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= 20 | go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= 21 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 22 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 23 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 24 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 25 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 26 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 27 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 28 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 29 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 30 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 31 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 32 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 33 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 34 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 35 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 36 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 37 | golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 38 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 39 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 40 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 41 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 42 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 43 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 44 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 45 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 46 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 47 | google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 48 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 49 | google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= 50 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 51 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 52 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 53 | -------------------------------------------------------------------------------- /stackdriver_test.go: -------------------------------------------------------------------------------- 1 | package stackdriverlog 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "net/http" 8 | "net/http/httptest" 9 | "strings" 10 | "testing" 11 | 12 | "github.com/google/go-cmp/cmp" 13 | "github.com/google/go-cmp/cmp/cmpopts" 14 | ) 15 | 16 | func TestIntegration(t *testing.T) { 17 | r, _ := http.NewRequest("GET", "/foo?bar=baz", nil) 18 | r.Header.Add("User-Agent", "test") 19 | w := httptest.NewRecorder() 20 | 21 | mux := http.NewServeMux() 22 | mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { 23 | logger := RequestContextLogger(r) 24 | logger.Debugf("1") 25 | logger.Infof("2") 26 | logger.Warnf("3") 27 | logger.Errorf("4") 28 | 29 | fmt.Fprintf(w, "OK\n") 30 | }) 31 | 32 | requestLogOut := new(bytes.Buffer) 33 | contextLogOut := new(bytes.Buffer) 34 | 35 | config := NewConfig("test") 36 | config.RequestLogOut = requestLogOut 37 | config.ContextLogOut = contextLogOut 38 | config.Severity = SeverityInfo 39 | config.AdditionalData = AdditionalData{ 40 | "service": "foo", 41 | "version": 1.0, 42 | } 43 | handler := RequestLogging(config)(mux) 44 | handler.ServeHTTP(w, r) 45 | 46 | // check request log 47 | var httpRequestLog HttpRequestLog 48 | err := json.Unmarshal(requestLogOut.Bytes(), &httpRequestLog) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | 53 | opts := []cmp.Option{ 54 | cmpopts.IgnoreFields(HttpRequestLog{}, "Time", "Trace"), 55 | cmpopts.IgnoreFields(HttpRequest{}, "RemoteIp", "ServerIp", "Latency"), 56 | } 57 | expected := HttpRequestLog{ 58 | Severity: "ERROR", 59 | AdditionalData: AdditionalData{ 60 | "service": "foo", 61 | "version": 1.0, 62 | }, 63 | HttpRequest: HttpRequest{ 64 | RequestMethod: "GET", 65 | RequestUrl: "/foo?bar=baz", 66 | RequestSize: "0", 67 | Status: 200, 68 | ResponseSize: "3", 69 | UserAgent: "test", 70 | Referer: "", 71 | CacheLookup: false, 72 | CacheHit: false, 73 | CacheValidatedWithOriginServer: false, 74 | Protocol: "HTTP/1.1", 75 | }, 76 | } 77 | 78 | if !cmp.Equal(httpRequestLog, expected, opts...) { 79 | t.Errorf("diff: %s", cmp.Diff(httpRequestLog, expected, opts...)) 80 | } 81 | 82 | if !strings.HasSuffix(httpRequestLog.HttpRequest.Latency, "s") { 83 | t.Errorf("invalid latency: %s", httpRequestLog.HttpRequest.Latency) 84 | } 85 | 86 | // check context log 87 | logs := strings.Split(string(contextLogOut.Bytes()), "\n") 88 | logs = logs[:len(logs)-1] 89 | logExpected := []struct { 90 | Severity string 91 | Message string 92 | }{ 93 | {"INFO", "2"}, 94 | {"WARNING", "3"}, 95 | {"ERROR", "4"}, 96 | } 97 | for idx, log := range logs { 98 | var cLog contextLog 99 | if err := json.Unmarshal([]byte(log), &cLog); err != nil { 100 | t.Fatal(err) 101 | } 102 | expected := contextLog{ 103 | Severity: logExpected[idx].Severity, 104 | Message: logExpected[idx].Message, 105 | AdditionalData: AdditionalData{ 106 | "service": "foo", 107 | "version": 1.0, 108 | }, 109 | } 110 | opts := []cmp.Option{ 111 | cmpopts.IgnoreFields(contextLog{}, "Time", "Trace", "SourceLocation"), 112 | } 113 | if !cmp.Equal(cLog, expected, opts...) { 114 | t.Errorf("diff: %s", cmp.Diff(cLog, expected, opts...)) 115 | } 116 | 117 | // check trace 118 | if httpRequestLog.Trace != cLog.Trace { 119 | t.Errorf("different trace: httpRequestLog=%s, contextLog=%s", httpRequestLog.Trace, cLog.Trace) 120 | } 121 | } 122 | } 123 | 124 | func TestNoContextLog(t *testing.T) { 125 | r, _ := http.NewRequest("GET", "/foo?bar=baz", nil) 126 | r.Header.Add("User-Agent", "test") 127 | w := httptest.NewRecorder() 128 | 129 | mux := http.NewServeMux() 130 | mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { 131 | fmt.Fprintf(w, "OK\n") 132 | }) 133 | 134 | requestLogOut := new(bytes.Buffer) 135 | contextLogOut := new(bytes.Buffer) 136 | 137 | config := NewConfig("test") 138 | config.RequestLogOut = requestLogOut 139 | config.ContextLogOut = contextLogOut 140 | handler := RequestLogging(config)(mux) 141 | handler.ServeHTTP(w, r) 142 | 143 | // check request log 144 | var httpRequestLog HttpRequestLog 145 | err := json.Unmarshal(requestLogOut.Bytes(), &httpRequestLog) 146 | if err != nil { 147 | t.Fatal(err) 148 | } 149 | 150 | opts := []cmp.Option{ 151 | cmpopts.IgnoreFields(HttpRequestLog{}, "Time", "Trace"), 152 | cmpopts.IgnoreFields(HttpRequest{}, "RemoteIp", "ServerIp", "Latency"), 153 | } 154 | expected := HttpRequestLog{ 155 | Severity: "DEFAULT", 156 | AdditionalData: nil, 157 | HttpRequest: HttpRequest{ 158 | RequestMethod: "GET", 159 | RequestUrl: "/foo?bar=baz", 160 | RequestSize: "0", 161 | Status: 200, 162 | ResponseSize: "3", 163 | UserAgent: "test", 164 | Referer: "", 165 | CacheLookup: false, 166 | CacheHit: false, 167 | CacheValidatedWithOriginServer: false, 168 | Protocol: "HTTP/1.1", 169 | }, 170 | } 171 | 172 | if !cmp.Equal(httpRequestLog, expected, opts...) { 173 | t.Errorf("diff: %s", cmp.Diff(httpRequestLog, expected, opts...)) 174 | } 175 | 176 | if len(contextLogOut.Bytes()) != 0 { 177 | t.Errorf("context log exists: %s", string(contextLogOut.Bytes())) 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | stackdriver-request-context-log 2 | === 3 | [![CircleCI](https://circleci.com/gh/yfuruyama/stackdriver-request-context-log.svg?style=svg)](https://circleci.com/gh/yfuruyama/stackdriver-request-context-log) 4 | 5 | Stackdriver Logging Go library for grouping a request log and application logs. 6 | 7 | With this library all application logs in the request are grouped and displayed under the request log (like App Engine). 8 | 9 | screenshot 10 | 11 | Note that the interface of this library is still **ALPHA** level quality. 12 | Breaking changes will be introduced frequently. 13 | 14 | ## Install 15 | 16 | ``` 17 | go get -u github.com/yfuruyama/stackdriver-request-context-log 18 | ``` 19 | 20 | ## Example 21 | 22 | This simple example shows how to integrate this library into your web application. 23 | 24 | ```go 25 | package main 26 | 27 | import ( 28 | "fmt" 29 | "net/http" 30 | "os" 31 | 32 | log "github.com/yfuruyama/stackdriver-request-context-log" 33 | ) 34 | 35 | func main() { 36 | mux := http.NewServeMux() 37 | 38 | // Set request handler 39 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 40 | // Get request context logger 41 | logger := log.RequestContextLogger(r) 42 | 43 | // These logs are grouped with the request log 44 | logger.Debugf("Hi") 45 | logger.Infof("Hello") 46 | logger.Warnf("World") 47 | 48 | fmt.Fprintf(w, "OK\n") 49 | }) 50 | 51 | projectId := "my-gcp-project" 52 | 53 | // Make config for this library 54 | config := log.NewConfig(projectId) 55 | config.RequestLogOut = os.Stderr // request log to stderr 56 | config.ContextLogOut = os.Stdout // context log to stdout 57 | config.Severity = log.SeverityInfo // only over INFO logs are logged 58 | config.AdditionalData = log.AdditionalData{ // set additional fields for all logs 59 | "service": "foo", 60 | "version": 1.0, 61 | } 62 | 63 | // Set middleware for the request log to be automatically logged 64 | handler := log.RequestLogging(config)(mux) 65 | 66 | // Run server 67 | fmt.Println("Waiting requests on port 8080...") 68 | if err := http.ListenAndServe(":8080", handler); err != nil { 69 | panic(err) 70 | } 71 | } 72 | ``` 73 | 74 | When this application receives a HTTP request `GET /`, following logs will be logged (with pretty print for display purposes only). 75 | 76 | ```json 77 | // STDOUT 78 | { 79 | "time": "2018-10-10T16:46:07.476567+09:00", 80 | "logging.googleapis.com/trace": "projects/my-gcp-project/traces/a8cb3e640add456cf7ed58e4a0589ea0", 81 | "logging.googleapis.com/sourceLocation": { 82 | "file": "main.go", 83 | "line": "21", 84 | "function": "main.main.func1" 85 | }, 86 | "severity": "INFO", 87 | "message": "Hello", 88 | "data": { 89 | "service": "foo", 90 | "version": 1 91 | } 92 | } 93 | { 94 | "time": "2018-10-10T16:46:07.476806+09:00", 95 | "logging.googleapis.com/trace": "projects/my-gcp-project/traces/a8cb3e640add456cf7ed58e4a0589ea0", 96 | "logging.googleapis.com/sourceLocation": { 97 | "file": "main.go", 98 | "line": "22", 99 | "function": "main.main.func1" 100 | }, 101 | "severity": "WARNING", 102 | "message": "World", 103 | "data": { 104 | "service": "foo", 105 | "version": 1 106 | } 107 | } 108 | 109 | // STDERR 110 | { 111 | "time": "2018-10-10T16:46:07.47682+09:00", 112 | "logging.googleapis.com/trace": "projects/my-gcp-project/traces/a8cb3e640add456cf7ed58e4a0589ea0", 113 | "severity": "WARNING", 114 | "httpRequest": { 115 | "requestMethod": "GET", 116 | "requestUrl": "/", 117 | "requestSize": "0", 118 | "status": 200, 119 | "responseSize": "3", 120 | "userAgent": "curl/7.58.0", 121 | "remoteIp": "[::1]:61352", 122 | "serverIp": "192.168.86.31", 123 | "referer": "", 124 | "latency": "0.000304s", 125 | "cacheLookup": false, 126 | "cacheHit": false, 127 | "cacheValidatedWithOriginServer": false, 128 | "protocol": "HTTP/1.1" 129 | }, 130 | "data": { 131 | "service": "foo", 132 | "version": 1 133 | } 134 | } 135 | ``` 136 | 137 | The log format is based on [LogEntry](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)'s structured payload so that you can pass these logs to [Stackdriver Logging agent](https://cloud.google.com/logging/docs/agent/). 138 | 139 | ## Stackdriver Logging agent setting 140 | 141 | ### GKE 142 | 143 | No settings required. All logs from `STDOUT` and `STDERR` are collected by default agents. 144 | 145 | ### GCE 146 | 147 | For GCE, you have to install agents manually ([docs](https://cloud.google.com/logging/docs/agent/installation)). 148 | Please install them and create config file like following, 149 | 150 | ``` 151 | # request log 152 | 153 | @type tail 154 | format json 155 | path /tmp/my_request_log 156 | pos_file /var/lib/google-fluentd/pos/my-request-log.pos 157 | read_from_head true 158 | time_format %Y-%m-%dT%H:%M:%S.%N%Z 159 | tag my-request-log 160 | 161 | 162 | # app log 163 | 164 | @type tail 165 | format json 166 | path /tmp/my_app_log 167 | pos_file /var/lib/google-fluentd/pos/my-app-log.pos 168 | read_from_head true 169 | time_format %Y-%m-%dT%H:%M:%S.%N%Z 170 | tag my-app-log 171 | 172 | ``` 173 | 174 | Don't forget to specify `time_format %Y-%m-%dT%H:%M:%S.%N%Z` to each `` directive. 175 | 176 | ## How logs are grouped 177 | 178 | This library leverages the grouping feature of Stackdriver Logging. 179 | See following references fore more details. 180 | 181 | * https://godoc.org/cloud.google.com/go/logging#hdr-Grouping_Logs_by_Request 182 | * https://cloud.google.com/appengine/articles/logging#linking_app_logs_and_requests 183 | 184 | ## Disclaimer 185 | 186 | This is not an official Google product. 187 | -------------------------------------------------------------------------------- /middleware.go: -------------------------------------------------------------------------------- 1 | package stackdriverlog 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "net" 8 | "net/http" 9 | "os" 10 | "strings" 11 | "time" 12 | 13 | "go.opencensus.io/exporter/stackdriver/propagation" 14 | "go.opencensus.io/trace" 15 | ) 16 | 17 | // RequestLogging creates the middleware which logs a request log and creates a request-context logger 18 | func RequestLogging(config *Config) func(http.Handler) http.Handler { 19 | return func(next http.Handler) http.Handler { 20 | fn := func(w http.ResponseWriter, r *http.Request) { 21 | before := time.Now() 22 | 23 | traceId := getTraceId(r) 24 | if traceId == "" { 25 | // there is no span yet, so create one 26 | var ctx context.Context 27 | traceId, ctx = generateTraceId(r) 28 | r = r.WithContext(ctx) 29 | } 30 | 31 | trace := fmt.Sprintf("projects/%s/traces/%s", config.ProjectId, traceId) 32 | 33 | contextLogger := &ContextLogger{ 34 | out: config.ContextLogOut, 35 | Trace: trace, 36 | Severity: config.Severity, 37 | AdditionalData: config.AdditionalData, 38 | loggedSeverity: make([]Severity, 0, 10), 39 | } 40 | ctx := context.WithValue(r.Context(), contextLoggerKey, contextLogger) 41 | r = r.WithContext(ctx) 42 | 43 | wrw := &wrappedResponseWriter{ResponseWriter: w} 44 | defer func() { 45 | // logging 46 | elapsed := time.Since(before) 47 | maxSeverity := contextLogger.maxSeverity() 48 | err := writeRequestLog(r, config, wrw.status, wrw.responseSize, elapsed, trace, maxSeverity) 49 | if err != nil { 50 | fmt.Fprintln(os.Stderr, err.Error()) 51 | } 52 | }() 53 | next.ServeHTTP(wrw, r) 54 | } 55 | return http.HandlerFunc(fn) 56 | } 57 | } 58 | 59 | func getTraceId(r *http.Request) string { 60 | span := trace.FromContext(r.Context()) 61 | if span != nil { 62 | return span.SpanContext().TraceID.String() 63 | } 64 | 65 | httpFormat := &propagation.HTTPFormat{} 66 | if sc, ok := httpFormat.SpanContextFromRequest(r); ok { 67 | return sc.TraceID.String() 68 | } 69 | 70 | return "" 71 | } 72 | 73 | func generateTraceId(r *http.Request) (string, context.Context) { 74 | ctx, span := trace.StartSpan(r.Context(), "") 75 | sc := span.SpanContext() 76 | return sc.TraceID.String(), ctx 77 | } 78 | 79 | type wrappedResponseWriter struct { 80 | http.ResponseWriter 81 | status int 82 | responseSize int 83 | } 84 | 85 | func (w *wrappedResponseWriter) WriteHeader(status int) { 86 | w.status = status 87 | w.ResponseWriter.WriteHeader(status) 88 | } 89 | 90 | func (w *wrappedResponseWriter) Write(b []byte) (int, error) { 91 | if w.status == 0 { 92 | w.status = http.StatusOK 93 | } 94 | n, err := w.ResponseWriter.Write(b) 95 | w.responseSize += n 96 | return n, err 97 | } 98 | 99 | type HttpRequest struct { 100 | RequestMethod string `json:"requestMethod"` 101 | RequestUrl string `json:"requestUrl"` 102 | RequestSize string `json:"requestSize"` 103 | Status int `json:"status"` 104 | ResponseSize string `json:"responseSize"` 105 | UserAgent string `json:"userAgent"` 106 | RemoteIp string `json:"remoteIp"` 107 | ServerIp string `json:"serverIp"` 108 | Referer string `json:"referer"` 109 | Latency string `json:"latency"` 110 | CacheLookup bool `json:"cacheLookup"` 111 | CacheHit bool `json:"cacheHit"` 112 | CacheValidatedWithOriginServer bool `json:"cacheValidatedWithOriginServer"` 113 | Protocol string `json:"protocol"` 114 | } 115 | 116 | type HttpRequestLog struct { 117 | Time string `json:"time"` 118 | Trace string `json:"logging.googleapis.com/trace"` 119 | Severity string `json:"severity"` 120 | HttpRequest HttpRequest `json:"httpRequest"` 121 | AdditionalData AdditionalData `json:"data,omitempty"` 122 | } 123 | 124 | func writeRequestLog(r *http.Request, config *Config, status int, responseSize int, elapsed time.Duration, trace string, severity Severity) error { 125 | requestLog := &HttpRequestLog{ 126 | Time: time.Now().Format(time.RFC3339Nano), 127 | Trace: trace, 128 | Severity: severity.String(), 129 | HttpRequest: HttpRequest{ 130 | RequestMethod: r.Method, 131 | RequestUrl: r.URL.RequestURI(), 132 | RequestSize: fmt.Sprintf("%d", r.ContentLength), 133 | Status: status, 134 | ResponseSize: fmt.Sprintf("%d", responseSize), 135 | UserAgent: r.UserAgent(), 136 | RemoteIp: getRemoteIp(r), 137 | ServerIp: getServerIp(), 138 | Referer: r.Referer(), 139 | Latency: fmt.Sprintf("%fs", elapsed.Seconds()), 140 | CacheLookup: false, 141 | CacheHit: false, 142 | CacheValidatedWithOriginServer: false, 143 | Protocol: r.Proto, 144 | }, 145 | AdditionalData: config.AdditionalData, 146 | } 147 | requestLogJson, err := json.Marshal(requestLog) 148 | if err != nil { 149 | return err 150 | } 151 | requestLogJson = append(requestLogJson, '\n') 152 | 153 | _, err = config.RequestLogOut.Write(requestLogJson) 154 | return err 155 | } 156 | 157 | func getRemoteIp(r *http.Request) string { 158 | parts := strings.Split(r.RemoteAddr, ":") 159 | return parts[0] 160 | } 161 | 162 | func getServerIp() string { 163 | ifaces, err := net.Interfaces() 164 | if err != nil { 165 | return "" 166 | } 167 | for _, i := range ifaces { 168 | addrs, err := i.Addrs() 169 | if err != nil { 170 | return "" 171 | } 172 | for _, addr := range addrs { 173 | if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 174 | if ipnet.IP.To4() != nil { 175 | return ipnet.IP.String() 176 | } 177 | } 178 | } 179 | } 180 | return "" 181 | } 182 | -------------------------------------------------------------------------------- /stackdriver.go: -------------------------------------------------------------------------------- 1 | // Package stackdriverlog provides application logger for Cloud Logging. 2 | package stackdriverlog 3 | 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "os" 10 | "runtime" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | type AdditionalData map[string]interface{} 16 | 17 | // Config is the configuration for `RequestLogging` middleware. 18 | type Config struct { 19 | ProjectId string 20 | 21 | // Output for request log 22 | RequestLogOut io.Writer 23 | 24 | // Output for context log (application log) 25 | ContextLogOut io.Writer 26 | 27 | Severity Severity 28 | AdditionalData AdditionalData 29 | } 30 | 31 | // NewConfig creates a config with default settings. 32 | func NewConfig(projectId string) *Config { 33 | return &Config{ 34 | ProjectId: projectId, 35 | Severity: SeverityInfo, 36 | RequestLogOut: os.Stderr, 37 | ContextLogOut: os.Stdout, 38 | AdditionalData: AdditionalData{}, 39 | } 40 | } 41 | 42 | // Severity is the level of log. More details: 43 | // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity 44 | type Severity int 45 | 46 | const ( 47 | SeverityDefault Severity = 0 48 | SeverityDebug Severity = 100 49 | SeverityInfo Severity = 200 50 | SeverityNotice Severity = 300 51 | SeverityWarning Severity = 400 52 | SeverityError Severity = 500 53 | SeverityCritical Severity = 600 54 | SeverityAlert Severity = 700 55 | SeverityEmergency Severity = 800 56 | ) 57 | 58 | // String returns text representation for the severity 59 | func (s Severity) String() string { 60 | switch s { 61 | case SeverityDefault: 62 | return "DEFAULT" 63 | case SeverityDebug: 64 | return "DEBUG" 65 | case SeverityInfo: 66 | return "INFO" 67 | case SeverityNotice: 68 | return "NOTICE" 69 | case SeverityWarning: 70 | return "WARNING" 71 | case SeverityError: 72 | return "ERROR" 73 | case SeverityCritical: 74 | return "CRITICAL" 75 | case SeverityAlert: 76 | return "ALERT" 77 | case SeverityEmergency: 78 | return "EMERGENCY" 79 | } 80 | return "UNKNOWN" 81 | } 82 | 83 | type SourceLocation struct { 84 | File string `json:"file"` 85 | Line string `json:"line"` 86 | Function string `json:"function"` 87 | } 88 | 89 | type contextLog struct { 90 | Time string `json:"time"` 91 | Trace string `json:"logging.googleapis.com/trace"` 92 | SourceLocation SourceLocation `json:"logging.googleapis.com/sourceLocation"` 93 | Severity string `json:"severity"` 94 | Message string `json:"message"` 95 | AdditionalData AdditionalData `json:"data,omitempty"` 96 | } 97 | 98 | // ContextLogger is the logger which is combined with the request 99 | type ContextLogger struct { 100 | out io.Writer 101 | Trace string 102 | Severity Severity 103 | AdditionalData AdditionalData 104 | loggedSeverity []Severity 105 | } 106 | 107 | // RequestContextLogger gets request-context logger for the request. 108 | // You must use `RequestLogging` middleware in advance for this function to work. 109 | func RequestContextLogger(r *http.Request) *ContextLogger { 110 | v, _ := r.Context().Value(contextLoggerKey).(*ContextLogger) 111 | return v 112 | } 113 | 114 | // Default logs a message at DEFAULT severity 115 | func (l *ContextLogger) Default(args ...interface{}) { 116 | l.write(SeverityDefault, fmt.Sprint(args...)) 117 | } 118 | 119 | // Defaultf logs a message at DEFAULT severity 120 | func (l *ContextLogger) Defaultf(format string, args ...interface{}) { 121 | l.write(SeverityDefault, fmt.Sprintf(format, args...)) 122 | } 123 | 124 | // Defaultln logs a message at DEFAULT severity 125 | func (l *ContextLogger) Defaultln(args ...interface{}) { 126 | l.write(SeverityDefault, fmt.Sprintln(args...)) 127 | } 128 | 129 | // Debug logs a message at DEBUG severity 130 | func (l *ContextLogger) Debug(args ...interface{}) { 131 | l.write(SeverityDebug, fmt.Sprint(args...)) 132 | } 133 | 134 | // Debugf logs a message at DEBUG severity 135 | func (l *ContextLogger) Debugf(format string, args ...interface{}) { 136 | l.write(SeverityDebug, fmt.Sprintf(format, args...)) 137 | } 138 | 139 | // Debugln logs a message at DEBUG severity 140 | func (l *ContextLogger) Debugln(args ...interface{}) { 141 | l.write(SeverityDebug, fmt.Sprintln(args...)) 142 | } 143 | 144 | // Info logs a message at INFO severity 145 | func (l *ContextLogger) Info(args ...interface{}) { 146 | l.write(SeverityInfo, fmt.Sprint(args...)) 147 | } 148 | 149 | // Infof logs a message at INFO severity 150 | func (l *ContextLogger) Infof(format string, args ...interface{}) { 151 | l.write(SeverityInfo, fmt.Sprintf(format, args...)) 152 | } 153 | 154 | // Infofln logs a message at INFO severity 155 | func (l *ContextLogger) Infoln(args ...interface{}) { 156 | l.write(SeverityInfo, fmt.Sprintln(args...)) 157 | } 158 | 159 | // Notice logs a message at NOTICE severity 160 | func (l *ContextLogger) Notice(args ...interface{}) { 161 | l.write(SeverityNotice, fmt.Sprint(args...)) 162 | } 163 | 164 | // Noticef logs a message at NOTICE severity 165 | func (l *ContextLogger) Noticef(format string, args ...interface{}) { 166 | l.write(SeverityNotice, fmt.Sprintf(format, args...)) 167 | } 168 | 169 | // Noticeln logs a message at NOTICE severity 170 | func (l *ContextLogger) Noticeln(args ...interface{}) { 171 | l.write(SeverityNotice, fmt.Sprintln(args...)) 172 | } 173 | 174 | // Warning logs a message at WARNING severity 175 | func (l *ContextLogger) Warning(args ...interface{}) { 176 | l.write(SeverityWarning, fmt.Sprint(args...)) 177 | } 178 | 179 | // Warningf logs a message at WARNING severity 180 | func (l *ContextLogger) Warningf(format string, args ...interface{}) { 181 | l.write(SeverityWarning, fmt.Sprintf(format, args...)) 182 | } 183 | 184 | // Warningln logs a message at WARNING severity 185 | func (l *ContextLogger) Warningln(args ...interface{}) { 186 | l.write(SeverityWarning, fmt.Sprintln(args...)) 187 | } 188 | 189 | // Warn logs a message at WARNING severity 190 | func (l *ContextLogger) Warn(args ...interface{}) { 191 | l.write(SeverityWarning, fmt.Sprint(args...)) 192 | } 193 | 194 | // Warnf logs a message at WARNING severity 195 | func (l *ContextLogger) Warnf(format string, args ...interface{}) { 196 | l.write(SeverityWarning, fmt.Sprintf(format, args...)) 197 | } 198 | 199 | // Warnln logs a message at WARNING severity 200 | func (l *ContextLogger) Warnln(args ...interface{}) { 201 | l.write(SeverityWarning, fmt.Sprintln(args...)) 202 | } 203 | 204 | // Error logs a message at ERROR severity 205 | func (l *ContextLogger) Error(args ...interface{}) { 206 | l.write(SeverityError, fmt.Sprint(args...)) 207 | } 208 | 209 | // Errorf logs a message at ERROR severity 210 | func (l *ContextLogger) Errorf(format string, args ...interface{}) { 211 | l.write(SeverityError, fmt.Sprintf(format, args...)) 212 | } 213 | 214 | // Errorln logs a message at ERROR severity 215 | func (l *ContextLogger) Errorln(args ...interface{}) { 216 | l.write(SeverityError, fmt.Sprintln(args...)) 217 | } 218 | 219 | // Critical logs a message at CRITICAL severity 220 | func (l *ContextLogger) Critical(args ...interface{}) { 221 | l.write(SeverityCritical, fmt.Sprint(args...)) 222 | } 223 | 224 | // Criticalf logs a message at CRITICAL severity 225 | func (l *ContextLogger) Criticalf(format string, args ...interface{}) { 226 | l.write(SeverityCritical, fmt.Sprintf(format, args...)) 227 | } 228 | 229 | // Criticalln logs a message at CRITICAL severity 230 | func (l *ContextLogger) Criticalln(args ...interface{}) { 231 | l.write(SeverityCritical, fmt.Sprintln(args...)) 232 | } 233 | 234 | // Alert logs a message at ALERT severity 235 | func (l *ContextLogger) Alert(args ...interface{}) { 236 | l.write(SeverityAlert, fmt.Sprint(args...)) 237 | } 238 | 239 | // Alertf logs a message at ALERT severity 240 | func (l *ContextLogger) Alertf(format string, args ...interface{}) { 241 | l.write(SeverityAlert, fmt.Sprintf(format, args...)) 242 | } 243 | 244 | // Alertln logs a message at ALERT severity 245 | func (l *ContextLogger) Alertln(args ...interface{}) { 246 | l.write(SeverityAlert, fmt.Sprintln(args...)) 247 | } 248 | 249 | // Emergency logs a message at EMERGENCY severity 250 | func (l *ContextLogger) Emergency(args ...interface{}) { 251 | l.write(SeverityEmergency, fmt.Sprint(args...)) 252 | } 253 | 254 | // Emergencyf logs a message at EMERGENCY severity 255 | func (l *ContextLogger) Emergencyf(format string, args ...interface{}) { 256 | l.write(SeverityEmergency, fmt.Sprintf(format, args...)) 257 | } 258 | 259 | // Emergencyln logs a message at EMERGENCY severity 260 | func (l *ContextLogger) Emergencyln(args ...interface{}) { 261 | l.write(SeverityEmergency, fmt.Sprintln(args...)) 262 | } 263 | 264 | func (l *ContextLogger) write(severity Severity, msg string) error { 265 | if severity < l.Severity { 266 | return nil 267 | } 268 | 269 | l.loggedSeverity = append(l.loggedSeverity, severity) 270 | 271 | // get source location 272 | var location SourceLocation 273 | if pc, file, line, ok := runtime.Caller(2); ok { 274 | if function := runtime.FuncForPC(pc); function != nil { 275 | location.Function = function.Name() 276 | } 277 | location.Line = fmt.Sprintf("%d", line) 278 | parts := strings.Split(file, "/") 279 | location.File = parts[len(parts)-1] // use short file name 280 | } 281 | 282 | log := &contextLog{ 283 | Time: time.Now().Format(time.RFC3339Nano), 284 | Trace: l.Trace, 285 | SourceLocation: location, 286 | Severity: severity.String(), 287 | Message: msg, 288 | AdditionalData: l.AdditionalData, 289 | } 290 | 291 | logJson, err := json.Marshal(log) 292 | if err != nil { 293 | fmt.Fprintln(os.Stderr, err.Error()) 294 | } 295 | logJson = append(logJson, '\n') 296 | 297 | _, err = l.out.Write(logJson) 298 | return err 299 | } 300 | 301 | func (l *ContextLogger) maxSeverity() Severity { 302 | max := SeverityDefault 303 | for _, s := range l.loggedSeverity { 304 | if s > max { 305 | max = s 306 | } 307 | } 308 | return max 309 | } 310 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------