前言

生产环境上所输出的日志级别较高不利于定位,会碰到这样一种场景,我们改配置修改日志级别,再重启,以期望定位问题,然而问题重启后不浮现了,所以热加载配置有必要添进去。

实践

直接上代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    "os/signal"
    "syscall"
    "time"
)

type Config struct {
    Mode string `json:"Mode"`
}

var (
    config     *Config
)

func loadConfig() {
    f, err := ioutil.ReadFile("config.json")
    if err != nil {
        fmt.Println("[TEST_SIGUSR] Load config: ", err)
    }
    err = json.Unmarshal(f, &config)
    if err != nil {
        fmt.Println("[TEST_SIGUSR] Para config failed: ", err)
    }

}
func init() {
    loadConfig()
    fmt.Println("[TEST_SIGUSR] Load config;Mode: ", config.Mode)
    s := make(chan os.Signal, 1)
    signal.Notify(s, syscall.SIGUSR2)
    go func() {
            for {
            <-s
            loadConfig()
            fmt.Println("[TEST_SIGUSR] ReLoad config;Mode: ", config.Mode)
        }
    }()

}
func main() {
    q := make(chan os.Signal, 1)
    signal.Notify(q, syscall.SIGINT)
    for {
        select {
        case <-q:
            fmt.Println("[TEST_SIGUSR] ---ibye----")
            os.Exit(1)
        default:
        }
        fmt.Println("[TEST_SIGUSR] ---waiting to reload----")
        time.Sleep(time.Second * 2)

    }

}

文件目录如下:

wenhao-MA:test_sigusr wenhao$ ll
total 4944
-rw-r--r--  1 wenhao  staff       18 11 22 13:39 config.json
-rwxr-xr-x  1 wenhao  staff  2520352 11 22 13:41 sigusr
-rw-r--r--  1 wenhao  staff      973 11 22 13:47 sigusr.go
wenhao-MA:test_sigusr wenhao$ cat config.json
{"Mode":"Debug"}
config.jsonModekill -USR2 $(pidof sigusr)
wenhao-MA:test_sigusr wenhao$./sigusr 
[TEST_SIGUSR] Load config;Mode:  Debug
[TEST_SIGUSR] ---waiting to reload----
[TEST_SIGUSR] ---waiting to reload----
[TEST_SIGUSR] ReLoad config;Mode:  ERROR