gojs/plugins.go
2024-06-26 12:04:45 +08:00

93 lines
3.0 KiB
Go

package gojs
import (
"apigo.cc/apigo/plugin"
"fmt"
"github.com/ssgo/log"
"github.com/ssgo/u"
)
func init() {
plugin.Register(plugin.Plugin{
Id: "console",
Name: "console api referer by nodejs console",
Objects: map[string]interface{}{
"print": func(args ...interface{}) {
fmt.Print(makeStringArray(args, u.TextNone, u.BgNone)...)
},
"println": func(args ...interface{}) {
fmt.Println(makeStringArray(args, u.TextNone, u.BgNone)...)
},
"log": func(args ...interface{}) {
fmt.Println(makeStringArray(args, u.TextNone, u.BgNone)...)
},
"info": func(args ...interface{}) {
fmt.Println(makeStringArray(args, u.TextCyan, u.BgNone)...)
},
"warn": func(args ...interface{}) {
fmt.Println(makeStringArray(args, u.TextBlack, u.BgYellow)...)
},
"error": func(args ...interface{}) {
fmt.Println(makeStringArray(args, u.TextWhite, u.BgRed)...)
},
"input": func(prompt *string) string {
if prompt != nil {
fmt.Print(*prompt)
}
line := ""
_, _ = fmt.Scanln(&line)
return line
},
},
})
plugin.Register(plugin.Plugin{
Id: "logger",
Name: "logger api by github.com/ssgo/log",
Objects: map[string]interface{}{
"debug": func(message string, args *map[string]interface{}, ctx *plugin.Context) {
if logger, ok := ctx.GetInject("*log.Logger").(*log.Logger); ok {
logger.Debug(message, makeMapToArray(args)...)
}
},
"info": func(message string, args *map[string]interface{}, ctx *plugin.Context) {
if logger, ok := ctx.GetInject("*log.Logger").(*log.Logger); ok {
logger.Info(message, makeMapToArray(args)...)
}
},
"warn": func(message string, args *map[string]interface{}, ctx *plugin.Context) {
if logger, ok := ctx.GetInject("*log.Logger").(*log.Logger); ok {
logger.Warning(message, makeMapToArray(args)...)
}
},
"error": func(message string, args *map[string]interface{}, ctx *plugin.Context) {
if logger, ok := ctx.GetInject("*log.Logger").(*log.Logger); ok {
logger.Error(message, makeMapToArray(args)...)
}
},
},
ConfigSample: `level: info # specify the log level (error/warning/info/debug), default: info
file: # specify the log file, default logs to standard output
splitTag: 20060102 # log file split format, refer to Golang date time format syntax, default does not split
sensitive: phone,password,secret,token,accessToken # fields to be desensitized in logs, separated by commas. The matching values in requests, responses, HTTP headers, and request/response JSON data indices will be desensitized
`,
Init: func(conf map[string]interface{}) {
logConf := log.Config{}
if conf["level"] != nil {
logConf.Level = u.String(conf["level"])
}
if conf["file"] != nil {
logConf.File = u.String(conf["file"])
}
if conf["splitTag"] != nil {
logConf.SplitTag = u.String(conf["splitTag"])
}
if conf["sensitive"] != nil {
logConf.Sensitive = u.String(conf["sensitive"])
}
log.DefaultLogger = log.NewLogger(logConf)
},
})
}