github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_log_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // static service testing.
     8  
     9  package ghttp_test
    10  
    11  import (
    12  	"fmt"
    13  	"github.com/gogf/gf/os/gtime"
    14  	"github.com/gogf/gf/text/gstr"
    15  	"testing"
    16  	"time"
    17  
    18  	"github.com/gogf/gf/frame/g"
    19  	"github.com/gogf/gf/net/ghttp"
    20  	"github.com/gogf/gf/os/gfile"
    21  	"github.com/gogf/gf/test/gtest"
    22  )
    23  
    24  func Test_Log(t *testing.T) {
    25  	gtest.C(t, func(t *gtest.T) {
    26  		logDir := gfile.TempDir(gtime.TimestampNanoStr())
    27  		p, _ := ports.PopRand()
    28  		s := g.Server(p)
    29  		s.BindHandler("/hello", func(r *ghttp.Request) {
    30  			r.Response.Write("hello")
    31  		})
    32  		s.BindHandler("/error", func(r *ghttp.Request) {
    33  			panic("custom error")
    34  		})
    35  		s.SetLogPath(logDir)
    36  		s.SetAccessLogEnabled(true)
    37  		s.SetErrorLogEnabled(true)
    38  		s.SetLogStdout(false)
    39  		s.SetPort(p)
    40  		s.Start()
    41  		defer s.Shutdown()
    42  		defer gfile.Remove(logDir)
    43  		time.Sleep(100 * time.Millisecond)
    44  		client := g.Client()
    45  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    46  
    47  		t.Assert(client.GetContent("/hello"), "hello")
    48  		t.Assert(client.GetContent("/error"), "custom error")
    49  
    50  		logPath1 := gfile.Join(logDir, gtime.Now().Format("Y-m-d")+".log")
    51  		t.Assert(gstr.Contains(gfile.GetContents(logPath1), "http server started listening on"), true)
    52  		t.Assert(gstr.Contains(gfile.GetContents(logPath1), "HANDLER"), true)
    53  
    54  		logPath2 := gfile.Join(logDir, "access-"+gtime.Now().Format("Ymd")+".log")
    55  		//fmt.Println(gfile.GetContents(logPath2))
    56  		t.Assert(gstr.Contains(gfile.GetContents(logPath2), " /hello "), true)
    57  
    58  		logPath3 := gfile.Join(logDir, "error-"+gtime.Now().Format("Ymd")+".log")
    59  		//fmt.Println(gfile.GetContents(logPath3))
    60  		t.Assert(gstr.Contains(gfile.GetContents(logPath3), "custom error"), true)
    61  	})
    62  }