1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-27 14:57:05 +00:00

thank you @dtrifonov for your donation ❤️

This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-11-06 14:19:53 +02:00
parent 3d5ed9926e
commit 7f523d52e1
8 changed files with 16 additions and 209 deletions

View File

@@ -5,9 +5,6 @@ import (
"github.com/kataras/iris/v12/middleware/accesslog"
)
// Default line format:
// Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
//
// Read the example and its comments carefully.
func makeAccessLog() *accesslog.AccessLog {
// Initialize a new access log middleware.
@@ -28,6 +25,9 @@ func makeAccessLog() *accesslog.AccessLog {
ac.KeepMultiLineError = true
ac.PanicLog = accesslog.LogHandler
// Default line format if formatter is missing:
// Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
//
// Set Custom Formatter:
ac.SetFormatter(&accesslog.JSON{
Indent: " ",

View File

@@ -1,90 +0,0 @@
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
func main() {
app := iris.New()
customLogger := logger.New(logger.Config{
// Status displays status code
Status: true,
// IP displays request's remote address
IP: true,
// Method displays the http method
Method: true,
// Path displays the request path
Path: true,
// Query appends the url query to the Path.
Query: true,
// Shows information about the executed route.
TraceRoute: true,
// if !empty then its contents derives from `ctx.Values().Get("logger_message")
// will be added to the logs.
MessageContextKeys: []string{"logger_message"},
// if !empty then its contents derives from `ctx.GetHeader("User-Agent")
MessageHeaderKeys: []string{"User-Agent"},
})
// Runs first on every request: parties & subdomains, route match or not and all http errors.
app.UseRouter(customLogger)
// Runs first on each matched route of this Party and its children on every request.
app.Use(routesMiddleware)
app.Get("/", indexMiddleware, index)
app.Get("/list", listMiddleware, list)
app.Get("/1", hello)
app.Get("/2", hello)
app.OnAnyErrorCode(customLogger, func(ctx iris.Context) {
// this should be added to the logs, at the end because of the `logger.Config#MessageContextKey`
ctx.Values().Set("logger_message",
"a dynamic message passed to the logs")
ctx.Writef("My Custom error page")
})
// http://localhost:8080
// http://localhost:8080/list
// http://localhost:8080/list?stop=true
// http://localhost:8080/1
// http://localhost:8080/2
// http://lcoalhost:8080/notfoundhere
// see the output on the console.
app.Listen(":8080")
}
func routesMiddleware(ctx iris.Context) {
ctx.Writef("Executing Route: %s\n", ctx.GetCurrentRoute().MainHandlerName())
ctx.Next()
}
func indexMiddleware(ctx iris.Context) {
ctx.WriteString("Index Middleware\n")
ctx.Next()
}
func index(ctx iris.Context) {
ctx.WriteString("Index Handler")
}
func listMiddleware(ctx iris.Context) {
ctx.WriteString("List Middleware\n")
if simulateStop, _ := ctx.URLParamBool("stop"); !simulateStop {
ctx.Next()
}
}
func list(ctx iris.Context) {
ctx.WriteString("List Handler")
}
func hello(ctx iris.Context) {
ctx.Writef("Hello from %s", ctx.Path())
}

View File

@@ -1,110 +0,0 @@
package main
import (
"fmt"
"io"
"os"
"strings"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
const deleteFileOnExit = false
func newRequestLogger(newWriter io.Writer) iris.Handler {
c := logger.Config{}
c.AddSkipper(func(ctx iris.Context) bool {
path := ctx.Path()
for _, ext := range excludeExtensions {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
})
c.LogFuncCtx = func(ctx iris.Context, latency time.Duration) {
datetime := time.Now().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
customHandlerMessage := ctx.Values().GetString("log_message")
file, line := ctx.HandlerFileLine()
source := fmt.Sprintf("%s:%d", file, line)
// this will just append a line without an array of javascript objects, readers of this file should read one line per log javascript object,
// however, you can improve it even more, this is just a simple example on how to use the `LogFuncCtx`.
jsonStr := fmt.Sprintf(`{"datetime":"%s","level":"%s","source":"%s","latency": "%s","status": %d,"method":"%s","path":"%s","message":"%s"}`,
datetime, "INFO", source, latency.String(), ctx.GetStatusCode(), ctx.Method(), ctx.Path(), customHandlerMessage)
fmt.Fprintln(newWriter, jsonStr)
}
return logger.New(c)
}
func h(ctx iris.Context) {
ctx.Values().Set("log_message", "something to give more info to the request logger")
ctx.Writef("Hello from %s", ctx.Path())
}
func main() {
app := iris.New()
logFile := newLogFile()
defer func() {
logFile.Close()
if deleteFileOnExit {
os.Remove(logFile.Name())
}
}()
r := newRequestLogger(logFile)
app.Use(r)
app.OnAnyErrorCode(r, func(ctx iris.Context) {
ctx.HTML("<h1> Error: Please try <a href ='/'> this </a> instead.</h1>")
})
app.Get("/", h)
app.Get("/1", h)
app.Get("/2", h)
app.Get("/", h)
// http://localhost:8080
// http://localhost:8080/1
// http://localhost:8080/2
// http://lcoalhost:8080/notfoundhere
app.Listen(":8080")
}
var excludeExtensions = [...]string{
".js",
".css",
".jpg",
".png",
".ico",
".svg",
}
// 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 + ".json"
}
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
}