Archived
1
This repository has been archived on 2022-11-04. You can view files and clone it, but cannot push or open issues or pull requests.
fwzookeeper/context/context.go

65 lines
1.8 KiB
Go

// Fantasy World Zookeeper Bot
// Copyright (c) 2018 Vladimir "fat0troll" Hodakov
package context
import (
"fmt"
"github.com/rs/zerolog"
"gopkg.in/yaml.v2"
"io/ioutil"
"lab.wtfteam.pro/fat0troll/fw_zookeeper/local/config"
"os"
"path/filepath"
"runtime"
)
// getMemoryUsage returns memory usage for logger.
func (c *Context) getMemoryUsage(e *zerolog.Event, level zerolog.Level, message string) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
e.Str("memalloc", fmt.Sprintf("%dMB", m.Alloc/1024/1024))
e.Str("memsys", fmt.Sprintf("%dMB", m.Sys/1024/1024))
e.Str("numgc", fmt.Sprintf("%d", m.NumGC))
}
// Init is an initialization function for core context
// Without these parts of the application we can't start at all
func (c *Context) Init() {
c.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
c.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage))
c.Logger.Info().Msgf("fw_zookeeper v. %s is starting...", VERSION)
}
// InitConfiguration reads configuration from YAML and parses it in
// config.Struct.
func (c *Context) InitConfiguration() bool {
c.Logger.Info().Msg("Loading configuration files...")
configPath := os.Getenv("BOT_CONFIG")
if configPath == "" {
configPath = "./example/fw_zookeeper.yaml"
}
normalizedConfigPath, _ := filepath.Abs(configPath)
c.Logger.Debug().Msgf("Configuration file path: %s", normalizedConfigPath)
// Read configuration file into []byte.
fileData, err := ioutil.ReadFile(normalizedConfigPath)
if err != nil {
c.Logger.Error().Err(err).Msg("Failed to read configuration file")
return false
}
c.Config = &config.Struct{}
err = yaml.Unmarshal(fileData, c.Config)
if err != nil {
c.Logger.Error().Err(err).Msg("Failed to parse configuration file")
return false
}
c.Logger.Info().Msg("Configuration file parsed successfully")
return true
}