diff --git a/glc/conf/config.go b/glc/conf/config.go index ff3dceb..2c73721 100644 --- a/glc/conf/config.go +++ b/glc/conf/config.go @@ -30,6 +30,8 @@ var saveDays int var enableLogin bool var username string var password string +var slaveHosts []string +var enableSlaveTransfer bool func init() { UpdateConfigByEnv() @@ -62,6 +64,29 @@ func UpdateConfigByEnv() { enableLogin = GetenvBool("GLC_ENABLE_LOGIN", false) // 是否开启用户密码登录,默认“false” username = Getenv("GLC_USERNAME", "glc") // 登录用户名,默认“glc” password = Getenv("GLC_PASSWORD", "glogcenter") // 登录密码,默认“glogcenter” + splitHost(Getenv("GLC_SLAVE_HOSTS", "")) // 从服务器地址,多个时逗号分开,默认“” + enableSlaveTransfer = GetenvBool("GLC_SLAVE_TRANSFER", false) // 是否开启转发日志到其他GLC服务,默认false + +} + +// 取配置: 是否开启转发日志到其他GLC服务,可通过环境变量“GLC_SLAVE_TRANSFER”设定,默认false +func IsEnableSlaveTransfer() bool { + return enableSlaveTransfer +} + +// 取配置: 从服务器地址,可通过环境变量“GLC_SLAVE_HOSTS”设定,默认“” +func GetSlaveHosts() []string { + return slaveHosts +} + +func splitHost(str string) { + hosts := strings.Split(str, ";") + for i := 0; i < len(hosts); i++ { + url := strings.TrimSpace(hosts[i]) + if url != "" { + slaveHosts = append(slaveHosts, url) + } + } } // 取配置: 是否开启用户密码登录,可通过环境变量“GLC_ENABLE_LOGIN”设定,默认“false” diff --git a/glc/www/controller/log_add_controller.go b/glc/www/controller/log_add_controller.go index 828cf89..2de264f 100644 --- a/glc/www/controller/log_add_controller.go +++ b/glc/www/controller/log_add_controller.go @@ -5,7 +5,10 @@ import ( "glc/gweb" "glc/ldb" "glc/ldb/storage/logdata" + "io" "log" + "net/http" + "strings" ) // 添加日志(JSON提交方式) @@ -26,7 +29,42 @@ func JsonLogAddController(req *gweb.HttpRequest) *gweb.HttpResult { return gweb.Error500(err.Error()) } + if conf.IsEnableSlaveTransfer() { + transferGlc(md) // 转发其他GLC服务 + } + engine := ldb.NewDefaultEngine() engine.AddTextLog(md.Date, md.Text, md.System) return gweb.Ok() } + +// 转发其他GLC服务 +func transferGlc(md *logdata.LogDataModel) { + hosts := conf.GetSlaveHosts() + for i := 0; i < len(hosts); i++ { + go httpPostJson(hosts[i]+conf.GetContextPath()+"/v1/log/add", md.ToJson()) + } +} + +func httpPostJson(url string, jsondata string) ([]byte, error) { + + // 请求 + req, err := http.NewRequest("POST", url, strings.NewReader(jsondata)) + if err != nil { + return nil, err + } + + // 请求头 + req.Header.Set("Content-Type", "application/json;charset=UTF-8") + req.Header.Set(conf.GetHeaderSecurityKey(), conf.GetSecurityKey()) + + // 读取响应内容 + client := http.Client{} + res, err := client.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + return io.ReadAll(res.Body) +}