package console import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" "src.dualinventive.com/go/lib/dilog" // Register the javascript native module `util` _ "github.com/dop251/goja_nodejs/util" ) type logfunc func(args ...interface{}) // Console is a wrapped logrus javascripts `console` module type Console struct { runtime *goja.Runtime util *goja.Object logger dilog.Logger } func (c *Console) dolog(call goja.FunctionCall, l logfunc) goja.Value { if format, ok := goja.AssertFunction(c.util.Get("format")); ok { ret, err := format(c.util, call.Arguments...) if err != nil { panic(err) } l(ret.String()) } else { panic(c.runtime.NewTypeError("util.format is not a function")) } return nil } func (c *Console) log(call goja.FunctionCall) goja.Value { return c.dolog(call, c.logger.Info) } func (c *Console) err(call goja.FunctionCall) goja.Value { return c.dolog(call, c.logger.Error) } func (c *Console) warn(call goja.FunctionCall) goja.Value { return c.dolog(call, c.logger.Warning) } // Enable the logger in the runtime func Enable(runtime *goja.Runtime, logger dilog.Logger) { c := &Console{ runtime: runtime, logger: logger, } c.util = require.Require(runtime, "util").(*goja.Object) module := runtime.NewObject() if err := module.Set("log", c.log); err != nil { panic(err) } if err := module.Set("error", c.err); err != nil { panic(err) } if err := module.Set("warn", c.warn); err != nil { panic(err) } runtime.Set("console", module) }