@@ -90,6 +90,42 @@ func RequestLoggingWithEcho(config *Config) echo.MiddlewareFunc {
90
90
}
91
91
}
92
92
93
+ // SetContext for CloudFunctions
94
+ func SetContext (config * Config , w http.ResponseWriter , r * http.Request ) {
95
+ before := time .Now ()
96
+
97
+ traceId := getTraceId (r )
98
+ if traceId == "" {
99
+ // there is no span yet, so create one
100
+ var ctx context.Context
101
+ traceId , ctx = generateTraceId (r )
102
+ r = r .WithContext (ctx )
103
+ }
104
+
105
+ traces := fmt .Sprintf ("projects/%s/traces/%s" , config .ProjectId , traceId )
106
+
107
+ contextLogger := & ContextLogger {
108
+ out : config .ContextLogOut ,
109
+ Trace : traces ,
110
+ Severity : config .Severity ,
111
+ AdditionalData : config .AdditionalData ,
112
+ loggedSeverity : make ([]Severity , 0 , 10 ),
113
+ }
114
+ ctx := context .WithValue (r .Context (), contextLoggerKey , contextLogger )
115
+ r = r .WithContext (ctx )
116
+
117
+ wrw := & wrappedResponseWriter {ResponseWriter : w }
118
+ defer func () {
119
+ // logging
120
+ elapsed := time .Since (before )
121
+ maxSeverity := contextLogger .maxSeverity ()
122
+ err := writeRequestLog (r , config , wrw .status , wrw .responseSize , elapsed , traces , maxSeverity )
123
+ if err != nil {
124
+ _ , _ = fmt .Fprintln (os .Stderr , err .Error ())
125
+ }
126
+ }()
127
+ }
128
+
93
129
func getTraceId (r * http.Request ) string {
94
130
span := trace .FromContext (r .Context ())
95
131
if span != nil {
0 commit comments