Go 日志和配置設(shè)計(jì)

2022-05-13 16:33 更新

日志和配置的重要性

前面已經(jīng)介紹過日志在我們程序開發(fā)中起著很重要的作用,通過日志我們可以記錄調(diào)試我們的信息,當(dāng)初介紹過一個(gè)日志系統(tǒng)seelog,根據(jù)不同的level輸出不同的日志,這個(gè)對于程序開發(fā)和程序部署來說至關(guān)重要。我們可以在程序開發(fā)中設(shè)置level低一點(diǎn),部署的時(shí)候把level設(shè)置高,這樣我們開發(fā)中的調(diào)試信息可以屏蔽掉。

配置模塊對于應(yīng)用部署牽涉到服務(wù)器不同的一些配置信息非常有用,例如一些數(shù)據(jù)庫配置信息、監(jiān)聽端口、監(jiān)聽地址等都是可以通過配置文件來配置,這樣我們的應(yīng)用程序就具有很強(qiáng)的靈活性,可以通過配置文件的配置部署在不同的機(jī)器上,可以連接不同的數(shù)據(jù)庫之類的。

beego的日志設(shè)計(jì)

beego的日志設(shè)計(jì)部署思路來自于seelog,根據(jù)不同的level來記錄日志,但是beego設(shè)計(jì)的日志系統(tǒng)比較輕量級,采用了系統(tǒng)的log.Logger接口,默認(rèn)輸出到os.Stdout,用戶可以實(shí)現(xiàn)這個(gè)接口然后通過beego.SetLogger設(shè)置自定義的輸出,詳細(xì)的實(shí)現(xiàn)如下所示:

// Log levels to control the logging output.
const (
    LevelTrace = iota
    LevelDebug
    LevelInfo
    LevelWarning
    LevelError
    LevelCritical
)

// logLevel controls the global log level used by the logger.
var level = LevelTrace

// LogLevel returns the global log level and can be used in
// own implementations of the logger interface.
func Level() int {
    return level
}

// SetLogLevel sets the global log level used by the simple
// logger.
func SetLevel(l int) {
    level = l
}

上面這一段實(shí)現(xiàn)了日志系統(tǒng)的日志分級,默認(rèn)的級別是Trace,用戶通過SetLevel可以設(shè)置不同的分級。

// logger references the used application logger.
var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)

// SetLogger sets a new logger.
func SetLogger(l *log.Logger) {
    BeeLogger = l
}

// Trace logs a message at trace level.
func Trace(v ...interface{}) {
    if level <= LevelTrace {
        BeeLogger.Printf("[T] %v\n", v)
    }
}

// Debug logs a message at debug level.
func Debug(v ...interface{}) {
    if level <= LevelDebug {
        BeeLogger.Printf("[D] %v\n", v)
    }
}

// Info logs a message at info level.
func Info(v ...interface{}) {
    if level <= LevelInfo {
        BeeLogger.Printf("[I] %v\n", v)
    }
}

// Warning logs a message at warning level.
func Warn(v ...interface{}) {
    if level <= LevelWarning {
        BeeLogger.Printf("[W] %v\n", v)
    }
}

// Error logs a message at error level.
func Error(v ...interface{}) {
    if level <= LevelError {
        BeeLogger.Printf("[E] %v\n", v)
    }
}

// Critical logs a message at critical level.
func Critical(v ...interface{}) {
    if level <= LevelCritical {
        BeeLogger.Printf("[C] %v\n", v)
    }
}

上面這一段代碼默認(rèn)初始化了一個(gè)BeeLogger對象,默認(rèn)輸出到os.Stdout,用戶可以通過beego.SetLogger來設(shè)置實(shí)現(xiàn)了logger的接口輸出。這里面實(shí)現(xiàn)了六個(gè)函數(shù):

  • Trace(一般的記錄信息,舉例如下:)
    • "Entered parse function validation block"
    • "Validation: entered second 'if'"
    • "Dictionary 'Dict' is empty. Using default value"
  • Debug(調(diào)試信息,舉例如下:)
    • "Web page requested:  http://somesite.com Params='...'"
    • "Response generated. Response size: 10000. Sending."
    • "New file received. Type:PNG Size:20000"
  • Info(打印信息,舉例如下:)
    • "Web server restarted"
    • "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
    • "Service paused. Waiting for 'resume' call"
  • Warn(警告信息,舉例如下:)
    • "Cache corrupted for file='test.file'. Reading from back-end"
    • "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
    • "No response from statistics server. Statistics not sent"
  • Error(錯(cuò)誤信息,舉例如下:)
    • "Internal error. Cannot process request #12345 Error:...."
    • "Cannot perform login: credentials DB not responding"
  • Critical(致命錯(cuò)誤,舉例如下:)
    • "Critical panic received: .... Shutting down"
    • "Fatal error: ... App is shutting down to prevent data corruption or loss"

可以看到每個(gè)函數(shù)里面都有對level的判斷,所以如果我們在部署的時(shí)候設(shè)置了level=LevelWarning,那么Trace、Debug、Info這三個(gè)函數(shù)都不會(huì)有任何的輸出,以此類推。

beego的配置設(shè)計(jì)

配置信息的解析,beego實(shí)現(xiàn)了一個(gè)key=value的配置文件讀取,類似ini配置文件的格式,就是一個(gè)文件解析的過程,然后把解析的數(shù)據(jù)保存到map中,最后在調(diào)用的時(shí)候通過幾個(gè)string、int之類的函數(shù)調(diào)用返回相應(yīng)的值,具體的實(shí)現(xiàn)請看下面:

首先定義了一些ini配置文件的一些全局性常量 :

var (
    bComment = []byte{'#'}
    bEmpty   = []byte{}
    bEqual   = []byte{'='}
    bDQuote  = []byte{'"'}
)

定義了配置文件的格式:

// A Config represents the configuration.
type Config struct {
    filename string
    comment  map[int][]string  // id: []{comment, key...}; id 1 is for main comment.
    data     map[string]string // key: value
    offset   map[string]int64  // key: offset; for editing.
    sync.RWMutex
}

定義了解析文件的函數(shù),解析文件的過程是打開文件,然后一行一行的讀取,解析注釋、空行和key=value數(shù)據(jù):

// ParseFile creates a new Config and parses the file configuration from the
// named file.
func LoadConfig(name string) (*Config, error) {
    file, err := os.Open(name)
    if err != nil {
        return nil, err
    }

    cfg := &Config{
        file.Name(),
        make(map[int][]string),
        make(map[string]string),
        make(map[string]int64),
        sync.RWMutex{},
    }
    cfg.Lock()
    defer cfg.Unlock()
    defer file.Close()

    var comment bytes.Buffer
    buf := bufio.NewReader(file)

    for nComment, off := 0, int64(1); ; {
        line, _, err := buf.ReadLine()
        if err == io.EOF {
            break
        }
        if bytes.Equal(line, bEmpty) {
            continue
        }

        off += int64(len(line))

        if bytes.HasPrefix(line, bComment) {
            line = bytes.TrimLeft(line, "#")
            line = bytes.TrimLeftFunc(line, unicode.IsSpace)
            comment.Write(line)
            comment.WriteByte('\n')
            continue
        }
        if comment.Len() != 0 {
            cfg.comment[nComment] = []string{comment.String()}
            comment.Reset()
            nComment++
        }

        val := bytes.SplitN(line, bEqual, 2)
        if bytes.HasPrefix(val[1], bDQuote) {
            val[1] = bytes.Trim(val[1], `"`)
        }

        key := strings.TrimSpace(string(val[0]))
        cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
        cfg.data[key] = strings.TrimSpace(string(val[1]))
        cfg.offset[key] = off
    }
    return cfg, nil
}

下面實(shí)現(xiàn)了一些讀取配置文件的函數(shù),返回的值確定為bool、int、float64或string:

// Bool returns the boolean value for a given key.
func (c *Config) Bool(key string) (bool, error) {
    return strconv.ParseBool(c.data[key])
}

// Int returns the integer value for a given key.
func (c *Config) Int(key string) (int, error) {
    return strconv.Atoi(c.data[key])
}

// Float returns the float value for a given key.
func (c *Config) Float(key string) (float64, error) {
    return strconv.ParseFloat(c.data[key], 64)
}

// String returns the string value for a given key.
func (c *Config) String(key string) string {
    return c.data[key]
}

應(yīng)用指南

下面這個(gè)函數(shù)是我一個(gè)應(yīng)用中的例子,用來獲取遠(yuǎn)程url地址的json數(shù)據(jù),實(shí)現(xiàn)如下:

func GetJson() {
    resp, err := http.Get(beego.AppConfig.String("url"))
    if err != nil {
        beego.Critical("http get info error")
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    err = json.Unmarshal(body, &AllInfo)
    if err != nil {
        beego.Critical("error:", err)
    }
}

函數(shù)中調(diào)用了框架的日志函數(shù)beego.Critical函數(shù)用來報(bào)錯(cuò),調(diào)用了beego.AppConfig.String("url")用來獲取配置文件中的信息,配置文件的信息如下(app.conf):

appname = hs
url ="http://www.api.com/api.html"
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號