1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-22 20:37:05 +00:00

logging: several improvements

Former-commit-id: 12538c74a1aa55314c35ac3cf2665646b704851d
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-04-28 01:58:56 +03:00
parent b02706f207
commit 27ca1c93f5
11 changed files with 125 additions and 56 deletions

View File

@@ -1,14 +1,24 @@
package main
import (
"os"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
func main() {
app := iris.New()
// Set Logger level to "debug",
// see your terminal and the created file.
app.Logger().SetLevel("debug")
// Write logs to a file too.
f := newLogFile()
defer f.Close()
app.Logger().AddOutput(f)
// Register a request logger middleware to the application.
app.Use(logger.New())
@@ -93,7 +103,7 @@ func main() {
usersRoutes.Delete("/{id:uint64}", func(ctx iris.Context) {
id, _ := ctx.Params().GetUint64("id")
ctx.Writef("delete user by id: %d", id)
}).SetDescription("Deletes a User")
}).SetDescription("deletes a user")
// Subdomains, depends on the host, you have to edit the hosts or nginx/caddy's configuration if you use them.
//
@@ -162,3 +172,21 @@ func info(ctx iris.Context) {
ctx.Writef("\nInfo\n\n")
ctx.Writef("Method: %s\nSubdomain: %s\nPath: %s\nParameters length: %d", method, subdomain, path, paramsLen)
}
// get a filename based on the date, file logs works that way the most times
// but these are just a sugar.
func todayFilename() string {
today := time.Now().Format("Jan 02 2006")
return today + ".txt"
}
func newLogFile() *os.File {
filename := todayFilename()
// open an output file, this will append to the today's file if server restarted.
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
return f
}

View File

@@ -33,9 +33,9 @@ func newApp() *iris.Application {
}
func getHandler(ctx iris.Context) {
ctx.Writef("From %s", ctx.GetCurrentRoute().Trace())
ctx.Writef("From GET: %s", ctx.GetCurrentRoute().MainHandlerName())
}
func anyHandler(ctx iris.Context) {
ctx.Writef("From %s", ctx.GetCurrentRoute().Trace())
ctx.Writef("From %s: %s", ctx.Method(), ctx.GetCurrentRoute().MainHandlerName())
}

View File

@@ -14,9 +14,9 @@ func TestRouteRegisterRuleExample(t *testing.T) {
for _, method := range router.AllMethods {
tt := e.Request(method, "/").Expect().Status(httptest.StatusOK).Body()
if method == "GET" {
tt.Equal("From [./main.go:28] GET: / -> github.com/kataras/iris/v12/_examples/routing/route-register-rule.getHandler()")
tt.Equal("From GET: github.com/kataras/iris/v12/_examples/routing/route-register-rule.getHandler")
} else {
tt.Equal("From [./main.go:30] " + method + ": / -> github.com/kataras/iris/v12/_examples/routing/route-register-rule.anyHandler()")
tt.Equal("From " + method + ": github.com/kataras/iris/v12/_examples/routing/route-register-rule.anyHandler")
}
}
}