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

reorganization of _examples and add some new examples such as iris+groupcache+mysql+docker

Former-commit-id: ed635ee95de7160cde11eaabc0c1dcb0e460a620
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-06-07 15:26:06 +03:00
parent 9fdcb4c7fb
commit ed45c77be5
328 changed files with 4262 additions and 41621 deletions

View File

@@ -0,0 +1,48 @@
package main
import (
"os"
"time"
"github.com/kataras/iris/v12"
)
func main() {
f := newLogFile()
defer f.Close()
app := iris.New()
// Attach the file as logger, remember, iris' app logger is just an io.Writer.
// Use the following code if you need to write the logs to file and console at the same time.
// app.Logger().SetOutput(io.MultiWriter(f, os.Stdout))
app.Logger().SetOutput(f)
app.Get("/ping", func(ctx iris.Context) {
// for the sake of simplicity, in order see the logs at the ./_today_.txt
ctx.Application().Logger().Infof("Request path: %s", ctx.Path())
ctx.WriteString("pong")
})
// Navigate to http://localhost:8080/ping
// and open the ./logs{TODAY}.txt file.
if err := app.Listen(":8080", iris.WithoutBanner); err != nil {
app.Logger().Warn("Shutdown with error: " + err.Error())
}
}
// Get a filename based on the date, just for the sugar.
func todayFilename() string {
today := time.Now().Format("Jan 02 2006")
return today + ".txt"
}
func newLogFile() *os.File {
filename := todayFilename()
// Open the 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

@@ -0,0 +1,87 @@
package main
import (
"encoding/json"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/requestid"
"github.com/kataras/golog"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
app.Logger().Handle(jsonOutput)
app.Use(requestid.New())
/* Example Output:
{
"timestamp": 1591422944,
"level": "debug",
"message": "This is a message with data",
"fields": {
"username": "kataras"
},
"stacktrace": [
{
"function": "main.main",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:16"
}
]
}
*/
app.Logger().Debugf("This is a %s with data (debug prints the stacktrace too)", "message", golog.Fields{
"username": "kataras",
})
/* Example Output:
{
"timestamp": 1591422944,
"level": "info",
"message": "An info message",
"fields": {
"home": "https://iris-go.com"
}
}
*/
app.Logger().Infof("An info message", golog.Fields{"home": "https://iris-go.com"})
app.Get("/ping", ping)
// Navigate to http://localhost:8080/ping.
app.Listen(":8080" /*, iris.WithoutBanner*/)
}
func jsonOutput(l *golog.Log) bool {
enc := json.NewEncoder(l.Logger.Printer) // you can change the output to a file as well.
enc.SetIndent("", " ")
err := enc.Encode(l)
return err == nil
}
func ping(ctx iris.Context) {
/* Example Output:
{
"timestamp": 1591423046,
"level": "debug",
"message": "Request path: /ping",
"fields": {
"request_id": "fc12d88a-a338-4bb9-aa5e-126f2104365c"
},
"stacktrace": [
{
"function": "main.ping",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:82"
},
...
]
}
*/
ctx.Application().Logger().Debugf("Request path: %s", ctx.Path(), golog.Fields{
"request_id": ctx.GetID(),
})
ctx.WriteString("pong")
}

View File

@@ -0,0 +1,65 @@
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,
// Columns: 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"},
})
app.Use(customLogger)
h := func(ctx iris.Context) {
ctx.Writef("Hello from %s", ctx.Path())
}
app.Get("/", h)
app.Get("/1", h)
app.Get("/2", h)
// http errors have their own handlers, therefore
// registering a middleare should be done manually.
/*
app.OnErrorCode(404 ,customLogger, func(ctx iris.Context) {
ctx.Writef("My Custom 404 error page ")
})
*/
// or catch all http errors:
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/1
// http://localhost:8080/2
// http://lcoalhost:8080/notfoundhere
// see the output on the console.
app.Listen(":8080")
}

View File

@@ -0,0 +1,110 @@
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
}

View File

@@ -0,0 +1,107 @@
package main
import (
"os"
"strings"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
const deleteFileOnExit = true
func main() {
app := iris.New()
r, close := newRequestLogger()
defer close()
app.Use(r)
app.OnAnyErrorCode(r, func(ctx iris.Context) {
ctx.HTML("<h1> Error: Please try <a href ='/'> this </a> instead.</h1>")
})
h := func(ctx iris.Context) {
ctx.Writef("Hello from %s", ctx.Path())
}
app.Get("/", h)
app.Get("/1", h)
app.Get("/2", h)
// http://localhost:8080
// http://localhost:8080/1
// http://localhost:8080/2
// http://lcoalhost:8080/notfoundhere
app.Listen(":8080")
}
// 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
}
var excludeExtensions = [...]string{
".js",
".css",
".jpg",
".png",
".ico",
".svg",
}
func newRequestLogger() (h iris.Handler, close func() error) {
close = func() error { return nil }
c := logger.Config{
Status: true,
IP: true,
Method: true,
Path: true,
Columns: true,
}
logFile := newLogFile()
close = func() error {
err := logFile.Close()
if deleteFileOnExit {
err = os.Remove(logFile.Name())
}
return err
}
c.LogFunc = func(endTime time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
output := logger.Columnize(endTime.Format("2006/01/02 - 15:04:05"), latency, status, ip, method, path, message, headerMessage)
logFile.Write([]byte(output))
} // or make use of the `LogFuncCtx`, see the '../request-logger-file-json' example for more.
// when we don't want to use to log requests to assets and etc.
c.AddSkipper(func(ctx iris.Context) bool {
path := ctx.Path()
for _, ext := range excludeExtensions {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
})
h = logger.New(c)
return
}