• 13.4 日志和配置设计
    • 日志和配置的重要性
    • beego的日志设计
    • beego的配置设计
    • 应用指南
    • links

    13.4 日志和配置设计

    日志和配置的重要性

    前面已经介绍过日志在我们程序开发中起着很重要的作用,通过日志我们可以记录调试我们的信息,当初介绍过一个日志系统seelog,根据不同的level输出不同的日志,这个对于程序开发和程序部署来说至关重要。我们可以在程序开发中设置level低一点,部署的时候把level设置高,这样我们开发中的调试信息可以屏蔽掉。

    配置模块对于应用部署牵涉到服务器不同的一些配置信息非常有用,例如一些数据库配置信息、监听端口、监听地址等都是可以通过配置文件来配置,这样我们的应用程序就具有很强的灵活性,可以通过配置文件的配置部署在不同的机器上,可以连接不同的数据库之类的。

    beego的日志设计

    beego的日志设计部署思路来自于seelog,根据不同的level来记录日志,但是beego设计的日志系统比较轻量级,采用了系统的log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后通过beego.SetLogger设置自定义的输出,详细的实现如下所示:

    1. // Log levels to control the logging output.
    2. const (
    3. LevelTrace = iota
    4. LevelDebug
    5. LevelInfo
    6. LevelWarning
    7. LevelError
    8. LevelCritical
    9. )
    10. // logLevel controls the global log level used by the logger.
    11. var level = LevelTrace
    12. // LogLevel returns the global log level and can be used in
    13. // own implementations of the logger interface.
    14. func Level() int {
    15. return level
    16. }
    17. // SetLogLevel sets the global log level used by the simple
    18. // logger.
    19. func SetLevel(l int) {
    20. level = l
    21. }

    上面这一段实现了日志系统的日志分级,默认的级别是Trace,用户通过SetLevel可以设置不同的分级。

    1. // logger references the used application logger.
    2. var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
    3. // SetLogger sets a new logger.
    4. func SetLogger(l *log.Logger) {
    5. BeeLogger = l
    6. }
    7. // Trace logs a message at trace level.
    8. func Trace(v ...interface{}) {
    9. if level <= LevelTrace {
    10. BeeLogger.Printf("[T] %v\n", v)
    11. }
    12. }
    13. // Debug logs a message at debug level.
    14. func Debug(v ...interface{}) {
    15. if level <= LevelDebug {
    16. BeeLogger.Printf("[D] %v\n", v)
    17. }
    18. }
    19. // Info logs a message at info level.
    20. func Info(v ...interface{}) {
    21. if level <= LevelInfo {
    22. BeeLogger.Printf("[I] %v\n", v)
    23. }
    24. }
    25. // Warning logs a message at warning level.
    26. func Warn(v ...interface{}) {
    27. if level <= LevelWarning {
    28. BeeLogger.Printf("[W] %v\n", v)
    29. }
    30. }
    31. // Error logs a message at error level.
    32. func Error(v ...interface{}) {
    33. if level <= LevelError {
    34. BeeLogger.Printf("[E] %v\n", v)
    35. }
    36. }
    37. // Critical logs a message at critical level.
    38. func Critical(v ...interface{}) {
    39. if level <= LevelCritical {
    40. BeeLogger.Printf("[C] %v\n", v)
    41. }
    42. }

    上面这一段代码默认初始化了一个BeeLogger对象,默认输出到os.Stdout,用户可以通过beego.SetLogger来设置实现了logger的接口输出。这里面实现了六个函数:

    • Trace(一般的记录信息,举例如下:)
      • “Entered parse function validation block”
      • “Validation: entered second ‘if’”
      • “Dictionary ‘Dict’ is empty. Using default value”
    • Debug(调试信息,举例如下:)
      • “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(错误信息,举例如下:)
      • “Internal error. Cannot process request #12345 Error:….”
      • “Cannot perform login: credentials DB not responding”
    • Critical(致命错误,举例如下:)
      • “Critical panic received: …. Shutting down”
      • “Fatal error: … App is shutting down to prevent data corruption or loss”

    可以看到每个函数里面都有对level的判断,所以如果我们在部署的时候设置了level=LevelWarning,那么Trace、Debug、Info这三个函数都不会有任何的输出,以此类推。

    beego的配置设计

    配置信息的解析,beego实现了一个key=value的配置文件读取,类似ini配置文件的格式,就是一个文件解析的过程,然后把解析的数据保存到map中,最后在调用的时候通过几个string、int之类的函数调用返回相应的值,具体的实现请看下面:

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

    1. var (
    2. bComment = []byte{'#'}
    3. bEmpty = []byte{}
    4. bEqual = []byte{'='}
    5. bDQuote = []byte{'"'}
    6. )

    定义了配置文件的格式:

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

    定义了解析文件的函数,解析文件的过程是打开文件,然后一行一行的读取,解析注释、空行和key=value数据:

    1. // ParseFile creates a new Config and parses the file configuration from the
    2. // named file.
    3. func LoadConfig(name string) (*Config, error) {
    4. file, err := os.Open(name)
    5. if err != nil {
    6. return nil, err
    7. }
    8. cfg := &Config{
    9. file.Name(),
    10. make(map[int][]string),
    11. make(map[string]string),
    12. make(map[string]int64),
    13. sync.RWMutex{},
    14. }
    15. cfg.Lock()
    16. defer cfg.Unlock()
    17. defer file.Close()
    18. var comment bytes.Buffer
    19. buf := bufio.NewReader(file)
    20. for nComment, off := 0, int64(1); ; {
    21. line, _, err := buf.ReadLine()
    22. if err == io.EOF {
    23. break
    24. }
    25. if bytes.Equal(line, bEmpty) {
    26. continue
    27. }
    28. off += int64(len(line))
    29. if bytes.HasPrefix(line, bComment) {
    30. line = bytes.TrimLeft(line, "#")
    31. line = bytes.TrimLeftFunc(line, unicode.IsSpace)
    32. comment.Write(line)
    33. comment.WriteByte('\n')
    34. continue
    35. }
    36. if comment.Len() != 0 {
    37. cfg.comment[nComment] = []string{comment.String()}
    38. comment.Reset()
    39. nComment++
    40. }
    41. val := bytes.SplitN(line, bEqual, 2)
    42. if bytes.HasPrefix(val[1], bDQuote) {
    43. val[1] = bytes.Trim(val[1], `"`)
    44. }
    45. key := strings.TrimSpace(string(val[0]))
    46. cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
    47. cfg.data[key] = strings.TrimSpace(string(val[1]))
    48. cfg.offset[key] = off
    49. }
    50. return cfg, nil
    51. }

    下面实现了一些读取配置文件的函数,返回的值确定为bool、int、float64或string:

    1. // Bool returns the boolean value for a given key.
    2. func (c *Config) Bool(key string) (bool, error) {
    3. return strconv.ParseBool(c.data[key])
    4. }
    5. // Int returns the integer value for a given key.
    6. func (c *Config) Int(key string) (int, error) {
    7. return strconv.Atoi(c.data[key])
    8. }
    9. // Float returns the float value for a given key.
    10. func (c *Config) Float(key string) (float64, error) {
    11. return strconv.ParseFloat(c.data[key], 64)
    12. }
    13. // String returns the string value for a given key.
    14. func (c *Config) String(key string) string {
    15. return c.data[key]
    16. }

    应用指南

    下面这个函数是我一个应用中的例子,用来获取远程url地址的json数据,实现如下:

    1. func GetJson() {
    2. resp, err := http.Get(beego.AppConfig.String("url"))
    3. if err != nil {
    4. beego.Critical("http get info error")
    5. return
    6. }
    7. defer resp.Body.Close()
    8. body, err := ioutil.ReadAll(resp.Body)
    9. err = json.Unmarshal(body, &AllInfo)
    10. if err != nil {
    11. beego.Critical("error:", err)
    12. }
    13. }

    函数中调用了框架的日志函数beego.Critical函数用来报错,调用了beego.AppConfig.String("url")用来获取配置文件中的信息,配置文件的信息如下(app.conf):

    1. appname = hs
    2. url ="http://www.api.com/api.html"
    • 目录
    • 上一章: controller设计
    • 下一节: 实现博客的增删改