```go
package middleware
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"net/http/httputil"
"os"
"time"
"github.com/kataras/iris/v12"
)
func DebugLogger(debugFile string, cutLength int) func(c iris.Context) {
if debugFile == "" {
debugFile = "debug.log"
}
f, err := os.Create(debugFile)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err.Error())
}
return func(c iris.Context) {
if f == nil {
_, _ = fmt.Fprintln(os.Stderr, err.Error())
c.Next()
return
}
requestDump, err := httputil.DumpRequest(c.Request(), true)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err.Error())
}
c.Record()
c.Next()
var respJsonBuffer bytes.Buffer
err = json.Indent(&respJsonBuffer, c.Recorder().Body(), "", " ")
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err.Error())
}
respJson := respJsonBuffer.String()
if cutLength > 0 && cutLength < len(respJson) {
respJson = respJson[0:cutLength]
}
debugLog := fmt.Sprintf("\n======= request - %s ======= %d\n%s"+
"\n======= response\n%s\n\n\n\n", time.Now().Format(time.RFC3339),
rand.Int63n(10000), requestDump, respJson)
_, _ = f.WriteString(debugLog)
}
}
```
有疑问加站长微信联系(非本文作者)