Skip to content

Commit

Permalink
1.read config with env (prod,test,dev).
Browse files Browse the repository at this point in the history
2.fixed custom loger formater #37
  • Loading branch information
yoyofx committed Aug 14, 2020
1 parent 08732bc commit 92047b6
Show file tree
Hide file tree
Showing 26 changed files with 234 additions and 84 deletions.
41 changes: 14 additions & 27 deletions Abstractions/Configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package Abstractions
import (
"fmt"
"github.com/spf13/viper"
"github.com/yoyofx/yoyogo/Utils"
)

type Configuration struct {
Expand All @@ -11,36 +12,24 @@ type Configuration struct {
}

func NewConfiguration(configContext *ConfigurationContext) *Configuration {

configName := configContext.configName + "_" + configContext.profile
exists, _ := Utils.PathExists("./" + configName + "." + configContext.configType)
if !exists {
configName = configContext.configName
}

defaultConfig := viper.New()
defaultConfig.AddConfigPath(".")
defaultConfig.SetConfigName(configContext.configName)
defaultConfig.SetConfigName(configName)
defaultConfig.SetConfigType(configContext.configType)
if err := defaultConfig.ReadInConfig(); err != nil {
return nil
}

profile := defaultConfig.Get("application.profile")
var profileConfig *viper.Viper
if profile != nil {
profileConfig = viper.New()
profileConfig.AddConfigPath(".")
configContext.profile = profile.(string)
profileConfig.SetConfigName(configContext.configName + "_" + configContext.profile)
profileConfig.SetConfigType(configContext.configType)
configs := defaultConfig.AllSettings()
// 将default中的配置全部以默认配置写入
for k, v := range configs {
profileConfig.Set(k, v)
}

if err := profileConfig.ReadInConfig(); err != nil {
profileConfig = defaultConfig
}
}

return &Configuration{
context: configContext,
config: profileConfig,
config: defaultConfig,
}
}

Expand All @@ -50,12 +39,6 @@ func (c *Configuration) Get(name string) interface{} {

func (c *Configuration) GetSection(name string) IConfiguration {
section := c.config.Sub(name)
section.SetConfigName(c.context.configName + "_" + c.context.profile)
configs := c.config.AllSettings()
// 将default中的配置全部以默认配置写入
for k, v := range configs {
section.Set(k, v)
}

if section != nil {
return &Configuration{config: section}
Expand All @@ -69,3 +52,7 @@ func (c *Configuration) Unmarshal(obj interface{}) {
fmt.Println("unmarshal config is failed, err:", err)
}
}

func (c *Configuration) GetProfile() string {
return c.context.profile
}
5 changes: 3 additions & 2 deletions Abstractions/ConfigurationBuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (builder *ConfigurationBuilder) AddEnvironment() *ConfigurationBuilder {

func (builder *ConfigurationBuilder) AddYamlFile(name string) *ConfigurationBuilder {
if builder.context.configType == "" {
builder.context.configType = "yaml"
builder.context.configType = "yml"
builder.context.configName = name
}
return builder
Expand All @@ -42,6 +42,7 @@ func (builder *ConfigurationBuilder) AddJsonFile(name string) *ConfigurationBuil
return builder
}

func (builder *ConfigurationBuilder) Build() *Configuration {
func (builder *ConfigurationBuilder) Build(env string) *Configuration {
builder.context.profile = env
return NewConfiguration(builder.context)
}
7 changes: 7 additions & 0 deletions Abstractions/Env/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package Env

const (
Dev = "dev"
Prod = "prod"
Test = "test"
)
13 changes: 6 additions & 7 deletions Abstractions/HostBuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package Abstractions

import (
"fmt"
YoyoGo "github.com/yoyofx/yoyogo"
"github.com/yoyofx/yoyogo"
"github.com/yoyofx/yoyogo/Abstractions/Env"
"github.com/yoyofx/yoyogo/Abstractions/configs"
"github.com/yoyofx/yoyogo/DependencyInjection"
"github.com/yoyofx/yoyogo/WebFramework/Context"
Expand Down Expand Up @@ -35,6 +36,7 @@ func (host *HostBuilder) Configure(configure interface{}) *HostBuilder {

func (host *HostBuilder) UseConfiguration(configuration IConfiguration) *HostBuilder {
host.Context.Configuration = configuration
host.Context.HostingEnvironment.Profile = configuration.GetProfile()
section := host.Context.Configuration.GetSection("application")
if section != nil {
config := &configs.HostConfig{}
Expand Down Expand Up @@ -81,13 +83,13 @@ func getLocalIP() string {
return localIp
}

// RunningHostEnvironmentSetting ,get running env setting.
// RunningHostEnvironmentSetting ,get running Env setting.
func RunningHostEnvironmentSetting(hostEnv *Context.HostEnvironment) {
hostEnv.Host = getLocalIP()
hostEnv.PID = os.Getpid()
}

//buildingHostEnvironmentSetting build each configuration by init , such as file or env or args ...
//buildingHostEnvironmentSetting build each configuration by init , such as file or Env or args ...
func buildingHostEnvironmentSetting(context *HostBuildContext) {
hostEnv := context.HostingEnvironment
hostEnv.Version = YoyoGo.Version
Expand All @@ -98,16 +100,13 @@ func buildingHostEnvironmentSetting(context *HostBuildContext) {
if config.Server.Address != "" {
hostEnv.Addr = config.Server.Address
}
if config.Profile != "" {
hostEnv.Profile = config.Profile
}
}

hostEnv.Port = strings.Replace(hostEnv.Addr, ":", "", -1)
hostEnv.Args = os.Args

if hostEnv.Profile == "" {
hostEnv.Profile = Context.Dev
hostEnv.Profile = Env.Dev
}

}
Expand Down
1 change: 1 addition & 0 deletions Abstractions/IConfiguration.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ type IConfiguration interface {
Get(name string) interface{}
GetSection(name string) IConfiguration
Unmarshal(interface{})
GetProfile() string
}
24 changes: 12 additions & 12 deletions Abstractions/IServiceHost.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"fmt"
"github.com/yoyofx/yoyogo"
"github.com/yoyofx/yoyogo/Abstractions/Platform/ConsoleColors"
"github.com/yoyofx/yoyogo/Abstractions/xlog"
"github.com/yoyofx/yoyogo/Utils"
"github.com/yoyofx/yoyogo/WebFramework/Context"
"log"
"strconv"
)

Expand All @@ -18,22 +18,22 @@ type IServiceHost interface {
SetAppMode(mode string)
}

func PrintLogo(l *log.Logger, env *Context.HostEnvironment) {
func PrintLogo(l xlog.ILogger, env *Context.HostEnvironment) {
logo, _ := base64.StdEncoding.DecodeString(YoyoGo.Logo)

fmt.Println(ConsoleColors.Blue(string(logo)))
fmt.Printf("%s (%s)", ConsoleColors.Green(":: YoyoGo ::"), ConsoleColors.Blue(env.Version))
fmt.Println(" ")
fmt.Println(" ")
l.Println(ConsoleColors.Green("Welcome to YoyoGo, starting application ..."))
l.Printf("yoyogo framework version : %s", ConsoleColors.Blue(env.Version))
l.Printf("machine host ip : %s", ConsoleColors.Blue(env.Host))
l.Printf("listening on port : %s", ConsoleColors.Blue(env.Port))
l.Printf("application running pid : %s", ConsoleColors.Blue(strconv.Itoa(env.PID)))
l.Printf("application name : %s", ConsoleColors.Blue(env.ApplicationName))
l.Printf("application environment : %s", ConsoleColors.Blue(env.Profile))
l.Printf("application exec path : %s", ConsoleColors.Yellow(Utils.GetCurrentDirectory()))
l.Printf("running in %s mode , change (Dev,Test,Prod) mode by HostBuilder.SetEnvironment .", ConsoleColors.Blue(env.Profile))
l.Println(ConsoleColors.Green("Starting HTTP server..."))
l.Debug(ConsoleColors.Green("Welcome to YoyoGo, starting application ..."))
l.Debug("yoyogo framework version : %s", ConsoleColors.Blue(env.Version))
l.Debug("machine host ip : %s", ConsoleColors.Blue(env.Host))
l.Debug("listening on port : %s", ConsoleColors.Blue(env.Port))
l.Debug("application running pid : %s", ConsoleColors.Blue(strconv.Itoa(env.PID)))
l.Debug("application name : %s", ConsoleColors.Blue(env.ApplicationName))
l.Debug("application environment : %s", ConsoleColors.Blue(env.Profile))
l.Debug("application exec path : %s", ConsoleColors.Yellow(Utils.GetCurrentDirectory()))
l.Debug("running in %s mode , change (Dev,Test,Prod) mode by HostBuilder.SetEnvironment .", ConsoleColors.Blue(env.Profile))
l.Debug(ConsoleColors.Green("Starting HTTP server..."))

}
1 change: 0 additions & 1 deletion Abstractions/configs/HostConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ package configs
type HostConfig struct {
Name string `mapstructure:"name"`
Metadata string `mapstructure:"metadata"`
Profile string `mapstructure:"profile"`
Server ServerConfig `mapstructure:"server"`
}
11 changes: 11 additions & 0 deletions Abstractions/xlog/ILogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package xlog

type ILogger interface {
Debug(format string, a ...interface{})
Info(format string, a ...interface{})
Warning(format string, a ...interface{})
Error(format string, a ...interface{})

SetCustomLogFormat(logFormatterFunc func(logInfo LogInfo) string)
SetDateFormat(format string)
}
101 changes: 101 additions & 0 deletions Abstractions/xlog/XLogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package xlog

import (
"fmt"
"github.com/yoyofx/yoyogo/Abstractions/Platform/ConsoleColors"
"log"
"os"
"time"
)

type XLogger struct {
logger *log.Logger
dateFormat string
class string
logFormatter func(LogInfo) string
}

var LoggerDefaultDateFormat = "2006/01/02 15:04:05.00"

type LogLevel int

// MessageLevel
const (
NOTSET = iota
DEBUG = LogLevel(10 * iota) // DEBUG = 10
INFO = LogLevel(10 * iota) // INFO = 20
WARNING = LogLevel(10 * iota) // WARNING = 30
ERROR = LogLevel(10 * iota) // ERROR = 40
)

var LevelString = map[LogLevel]string{
DEBUG: "DEBUG",
INFO: "INFO",
WARNING: ConsoleColors.Yellow("WARNING"),
ERROR: ConsoleColors.Red("ERROR"),
}

func defaultLogFormater(logInfo LogInfo) string {
outLog := fmt.Sprintf(ConsoleColors.Yellow("[yoyogo] ")+"[%s] [%s] [%s] [%s] , %s",
logInfo.StartTime, logInfo.Level, logInfo.Class, logInfo.Host, logInfo.Message)
return outLog
}

func (log *XLogger) SetCustomLogFormat(logFormatterFunc func(logInfo LogInfo) string) {
log.logFormatter = logFormatterFunc
}

func (log *XLogger) SetDateFormat(format string) {
log.dateFormat = format
}

func NewXLogger() *XLogger {
logger := NewLoggerWith(log.New(os.Stdout, "", 0))
return logger
}

func NewLoggerWith(log *log.Logger) *XLogger {
logger := &XLogger{logger: log, dateFormat: LoggerDefaultDateFormat}
logger.SetCustomLogFormat(defaultLogFormater)
return logger
}

func GetXLogger(class string) ILogger {
logger := NewXLogger()
logger.class = class
return logger
}

func (log *XLogger) log(level LogLevel, format string, a ...interface{}) {
hostName, _ := os.Hostname()
message := format
if len(a[0].([]interface{})) > 0 {
message = fmt.Sprintf(format, a...)
}

start := time.Now()
info := LogInfo{
StartTime: start.Format(log.dateFormat),
Level: LevelString[level],
Class: log.class,
Host: hostName,
Message: message,
}
log.logger.Println(log.logFormatter(info))
}

func (log *XLogger) Debug(format string, a ...interface{}) {
log.log(DEBUG, format, a)
}

func (log *XLogger) Info(format string, a ...interface{}) {
log.log(INFO, format, a)
}

func (log *XLogger) Warning(format string, a ...interface{}) {
log.log(WARNING, format, a)
}

func (log *XLogger) Error(format string, a ...interface{}) {
log.log(ERROR, format, a)
}
9 changes: 9 additions & 0 deletions Abstractions/xlog/logInfo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package xlog

type LogInfo struct {
StartTime string
Level string
Class string
Host string
Message string
}
11 changes: 0 additions & 11 deletions Examples/SimpleWeb/config.yml

This file was deleted.

8 changes: 7 additions & 1 deletion Examples/SimpleWeb/config_dev.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
application:
name: demo_dev
metadata: "develop"
server:
address: ":8080"
type: "fasthttp"
address: ":8080"
max_request_size: 2096157
static:
patten: "/"
webroot: "./Static"
8 changes: 7 additions & 1 deletion Examples/SimpleWeb/config_prod.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
application:
name: demo_prod
metadata: "prod Env"
server:
address: ":8081"
type: "fasthttp"
address: ":8080"
max_request_size: 2096157
static:
patten: "/"
webroot: "./Static"
Loading

0 comments on commit 92047b6

Please sign in to comment.