1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-09 21:15:56 +00:00

mvc: struct field and method dependency logs on debug level. Read HISTORY.md

- remove Party.GetReporter

- Read HISTORY.md
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-08-24 21:44:29 +03:00
parent ef5685bf7e
commit 5e82fa5b89
24 changed files with 435 additions and 167 deletions

View File

@@ -11,7 +11,6 @@ import (
"time"
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/core/errgroup"
"github.com/kataras/iris/v12/hero"
"github.com/kataras/iris/v12/macro"
macroHandler "github.com/kataras/iris/v12/macro/handler"
@@ -169,12 +168,6 @@ type APIBuilder struct {
// the api builder global routes repository
routes *repository
// the api builder global errors, can be filled by the Subdomain, WildcardSubdomain, Handle...
// the list of possible errors that can be
// collected on the build state to log
// to the end-user.
errors *errgroup.Group
// the per-party handlers, order
// of handlers registration matters.
middleware context.Handlers
@@ -236,10 +229,9 @@ func NewAPIBuilder(logger *golog.Logger) *APIBuilder {
logger: logger,
parent: nil,
macros: macro.Defaults,
errors: errgroup.New("API Builder"),
relativePath: "/",
routes: new(repository),
apiBuilderDI: &APIContainer{Container: hero.New()},
apiBuilderDI: &APIContainer{Container: hero.New().WithLogger(logger)},
routerFilters: make(map[Party]*Filter),
partyMatcher: defaultPartyMatcher,
}
@@ -296,11 +288,6 @@ func (api *APIBuilder) GetRelPath() string {
return api.relativePath
}
// GetReporter returns the reporter for adding or receiving any errors caused when building the API.
func (api *APIBuilder) GetReporter() *errgroup.Group {
return api.errors
}
// AllowMethods will re-register the future routes that will be registered
// via `Handle`, `Get`, `Post`, ... to the given "methods" on that Party and its children "Parties",
// duplicates are not registered.
@@ -394,7 +381,7 @@ func (api *APIBuilder) handle(errorCode int, method string, relativePath string,
route.topLink = api.routes.getRelative(route)
if route, err = api.routes.register(route, api.routeRegisterRule); err != nil {
api.errors.Add(err)
api.logger.Error(err)
break
}
}
@@ -492,7 +479,7 @@ func (api *APIBuilder) HandleDir(requestPath string, fs http.FileSystem, opts ..
}
if _, err := api.routes.register(route, api.routeRegisterRule); err != nil {
api.errors.Add(err)
api.logger.Error(err)
break
}
}
@@ -533,7 +520,7 @@ func (api *APIBuilder) createRoutes(errorCode int, methods []string, relativePat
fullpath := api.relativePath + relativePath // for now, keep the last "/" if any, "/xyz/"
if len(handlers) == 0 {
api.errors.Addf("missing handlers for route[%s:%d] %s: %s", filename, line, strings.Join(methods, ", "), fullpath)
api.logger.Errorf("missing handlers for route[%s:%d] %s: %s", filename, line, strings.Join(methods, ", "), fullpath)
return nil
}
@@ -586,7 +573,7 @@ func (api *APIBuilder) createRoutes(errorCode int, methods []string, relativePat
for i, m := range methods { // single, empty method for error handlers.
route, err := NewRoute(errorCode, m, subdomain, path, routeHandlers, *api.macros)
if err != nil { // template path parser errors:
api.errors.Addf("[%s:%d] %v -> %s:%s:%s", filename, line, err, m, subdomain, path)
api.logger.Errorf("[%s:%d] %v -> %s:%s:%s", filename, line, err, m, subdomain, path)
continue
}
@@ -678,7 +665,6 @@ func (api *APIBuilder) Party(relativePath string, handlers ...context.Handler) P
routes: api.routes,
beginGlobalHandlers: api.beginGlobalHandlers,
doneGlobalHandlers: api.doneGlobalHandlers,
errors: api.errors,
routerFilters: api.routerFilters, // shared.
partyMatcher: api.partyMatcher, // shared.
// per-party/children
@@ -730,7 +716,7 @@ func (api *APIBuilder) PartyFunc(relativePath string, partyBuilderFunc func(p Pa
func (api *APIBuilder) Subdomain(subdomain string, middleware ...context.Handler) Party {
if api.relativePath == SubdomainWildcardIndicator {
// cannot concat wildcard subdomain with something else
api.errors.Addf("cannot concat parent wildcard subdomain with anything else -> %s , %s",
api.logger.Errorf("cannot concat parent wildcard subdomain with anything else -> %s , %s",
api.relativePath, subdomain)
return api
}
@@ -750,7 +736,7 @@ func (api *APIBuilder) Subdomain(subdomain string, middleware ...context.Handler
func (api *APIBuilder) WildcardSubdomain(middleware ...context.Handler) Party {
if hasSubdomain(api.relativePath) {
// cannot concat static subdomain with a dynamic one, wildcard should be at the root level
api.errors.Addf("cannot concat static subdomain with a dynamic one. Dynamic subdomains should be at the root level -> %s",
api.logger.Errorf("cannot concat static subdomain with a dynamic one. Dynamic subdomains should be at the root level -> %s",
api.relativePath)
return api
}
@@ -1184,7 +1170,7 @@ func (api *APIBuilder) Favicon(favPath string, requestPath ...string) *Route {
favPath = Abs(favPath)
f, err := os.Open(favPath)
if err != nil {
api.errors.Addf("favicon: file or directory %s not found: %w", favPath, err)
api.logger.Errorf("favicon: file or directory %s not found: %w", favPath, err)
return nil
}
@@ -1201,7 +1187,7 @@ func (api *APIBuilder) Favicon(favPath string, requestPath ...string) *Route {
// So we could panic but we don't,
// we just interrupt with a message
// to the (user-defined) logger.
api.errors.Addf("favicon: couldn't read the data bytes for %s: %w", favPath, err)
api.logger.Errorf("favicon: couldn't read the data bytes for %s: %w", favPath, err)
return nil
}
@@ -1261,7 +1247,7 @@ func (api *APIBuilder) OnAnyErrorCode(handlers ...context.Handler) (routes []*Ro
// Read `Configuration.ViewEngineContextKey` documentation for more.
func (api *APIBuilder) RegisterView(viewEngine context.ViewEngine) {
if err := viewEngine.Load(); err != nil {
api.errors.Add(err)
api.logger.Error(err)
return
}

View File

@@ -227,7 +227,7 @@ func (h *routerHandler) Build(provider RoutesProvider) error {
}
// TODO: move this and make it easier to read when all cases are, visually, tested.
if logger := h.logger; logger != nil && logger.Level == golog.DebugLevel {
if logger := h.logger; logger != nil && logger.Level == golog.DebugLevel && noLogCount < len(registeredRoutes) {
// group routes by method and print them without the [DBUG] and time info,
// the route logs are colorful.
// Note: don't use map, we need to keep registered order, use
@@ -291,7 +291,7 @@ func (h *routerHandler) Build(provider RoutesProvider) error {
m.method = "ERROR"
}
fmt.Fprintf(logger.Printer, "%d ", len(m.routes))
pio.WriteRich(logger.Printer, m.method, traceMethodColor(m.method))
pio.WriteRich(logger.Printer, m.method, TraceTitleColorCode(m.method))
}
fmt.Fprint(logger.Printer, ")\n")

View File

@@ -4,7 +4,6 @@ import (
"net/http"
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/core/errgroup"
"github.com/kataras/iris/v12/macro"
"github.com/kataras/golog"
@@ -36,8 +35,6 @@ type Party interface {
// if r := app.Party("/users"), then the `r.GetRelPath()` is the "/users".
// if r := app.Party("www.") or app.Subdomain("www") then the `r.GetRelPath()` is the "www.".
GetRelPath() string
// GetReporter returns the reporter for adding or receiving any errors caused when building the API.
GetReporter() *errgroup.Group
// Macros returns the macro collection that is responsible
// to register custom macros with their own parameter types and their macro functions for all routes.
//

View File

@@ -19,7 +19,7 @@ import (
// If any of the following fields are changed then the
// caller should Refresh the router.
type Route struct {
Title string `json"title"` // custom name to replace the method on debug logging.
Title string `json:"title"` // custom name to replace the method on debug logging.
Name string `json:"name"` // "userRoute"
Description string `json:"description"` // "lists a user"
Method string `json:"method"` // "GET"
@@ -202,10 +202,10 @@ func (r *Route) BuildHandlers() {
// String returns the form of METHOD, SUBDOMAIN, TMPL PATH.
func (r *Route) String() string {
start := r.Method
if r.StatusCode > 0 {
start = http.StatusText(r.StatusCode)
}
start := r.GetTitle()
// if r.StatusCode > 0 {
// start = fmt.Sprintf("%d (%s)", r.StatusCode, http.StatusText(r.StatusCode))
// }
return fmt.Sprintf("%s %s%s",
start, r.Subdomain, r.Tmpl().Src)
@@ -375,7 +375,8 @@ var methodColors = map[string]int{
MethodNone: 203, // orange-red.
}
func traceMethodColor(method string) int {
// TraceTitleColorCode returns the color code depending on the method or the status.
func TraceTitleColorCode(method string) int {
if color, ok := methodColors[method]; ok {
return color
}
@@ -383,6 +384,20 @@ func traceMethodColor(method string) int {
return 131 // for error handlers, of "ERROR [%STATUSCODE]"
}
// GetTitle returns the custom Title or the method or the error code.
func (r *Route) GetTitle() string {
title := r.Title
if title == "" {
if r.StatusCode > 0 {
title = fmt.Sprintf("%d", r.StatusCode) // if error code then title is the status code, e.g. 400.
} else {
title = r.Method // else is its method, e.g. GET
}
}
return title
}
// Trace prints some debug info about the Route to the "w".
// Should be called after `Build` state.
//
@@ -391,17 +406,10 @@ func traceMethodColor(method string) int {
// * @second_handler ...
// If route and handler line:number locations are equal then the second is ignored.
func (r *Route) Trace(w io.Writer, stoppedIndex int) {
title := r.Title
if title == "" {
if r.StatusCode > 0 {
title = fmt.Sprintf("%d", r.StatusCode) // if error code then title is the status code, e.g. 400.
} else {
title = r.Method // else is its method, e.g. GET
}
}
title := r.GetTitle()
// Color the method.
color := traceMethodColor(title)
color := TraceTitleColorCode(title)
// @method: @path
// space := strings.Repeat(" ", len(http.MethodConnect)-len(method))

View File

@@ -43,9 +43,9 @@ func TestRegisterRule(t *testing.T) {
if route := v1.Get("/", getHandler); route != nil {
t.Fatalf("expected duplicated route, with RouteError rule, to be nil but got: %#+v", route)
}
if expected, got := 1, len(v1.GetReporter().Errors); expected != got {
t.Fatalf("expected api builder's errors length to be: %d but got: %d", expected, got)
}
// if expected, got := 1, len(v1.GetReporter().Errors); expected != got {
// t.Fatalf("expected api builder's errors length to be: %d but got: %d", expected, got)
// }
}
func testRegisterRule(e *httptest.Expect, expectedGetBody string) {