edge/pkg/module/console.go

52 lines
1.0 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
package module
import (
"context"
"fmt"
"strings"
"gitlab.com/wpetit/goweb/logger"
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/dop251/goja"
"github.com/pkg/errors"
)
type ConsoleModule struct{}
func (m *ConsoleModule) Name() string {
return "console"
}
func (m *ConsoleModule) log(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
var sb strings.Builder
fields := make([]logger.Field, 0)
stack := rt.CaptureCallStack(0, nil)
if len(stack) > 1 {
fields = append(fields, logger.F("source", stack[1].Position().String()))
}
for _, arg := range call.Arguments {
sb.WriteString(fmt.Sprintf("%+v", arg.Export()))
sb.WriteString(" ")
}
logger.Debug(context.Background(), sb.String(), fields...)
return nil
}
func (m *ConsoleModule) Export(export *goja.Object) {
if err := export.Set("log", m.log); err != nil {
panic(errors.Wrap(err, "could not set 'log' function"))
}
}
func ConsoleModuleFactory() app.ServerModuleFactory {
return func(server *app.Server) app.ServerModule {
return &ConsoleModule{}
}
}