本文在介紹關于搭建golang框架的基礎上,重點探討了初始化日志、配置入口文件以及測試文件的方法,步驟簡單易上手操作,文章內容步步緊湊,希望大家根據這篇文章可以有所收獲。
入口文件
func main() {
config.InitConfig()
logger.InitLogger()
}暫且忽略一些實現細節,我們需要先初始化配置和日志,先來看看日志,我選用Uber的zap日志庫。來看看日志模塊怎么寫?
package logger
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var l *zap.Logger
func InitLogger(logPath, logLevel string) error {
hook := lumberjack.Logger{
Filename: logPath,
MaxSize: 1024,
MaxBackups: 3,
MaxAge: 7,
Compress: true,
}
w := zapcore.AddSync(&hook)
var level zapcore.Level
switch logLevel {
case "debug":
level = zap.DebugLevel
case "info":
level = zap.InfoLevel
case "error":
level = zap.ErrorLevel
default:
level = zap.DebugLevel
}
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
core := zapcore.NewCore(
zapcore.NewConsoleEncoder(encoderConfig),
w,
level,
)
l = zap.New(core)
return nil
}
func GetLogger() *zap.Logger {
return l
}我們先定義一個包級的全局變量l,類型是*zap.Logger,并創建了InitLogger和GetLogger這兩個函數。因為,zap不支持日志歸檔,所以在InitLogger中定義了一個lumberjack的hook,用來歸檔日志。我們可以看到InitLogger這個方法有兩個入參:logPath和logLevel。一般來講,這些參數應該是放在配置文件里的,接下來我們來寫配置。
我們簡單地創建一個config.json文件來存放配置:
config.json:
{
"log_config": {
"log_path": "{your_path}",
"log_level": "debug"
}
}然后在config.go中創建相應的結構體,之后定義InitConfig和GetConfig方法,在InitConfig方法中,我讀取了配置文件的內容,然后解析到結構體中,并處理了錯誤,如果有錯誤信息的話,我會將錯誤信息包裹一層,方便以后的錯誤定位。InitConfig有一個入參,就是配置文件的路徑,這個參數我會從命令行中獲取。
config.go:
package config
import (
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
)
type LogConfig struct {
LogPath string `json:"log_path"`
LogLevel string `json:"log_level"`
}
type Config struct {
LogConfig LogConfig `json:"log_config"`
}
var conf Config
func InitConfig(configPath string) error {
configFile, err := ioutil.ReadFile(configPath)
if err != nil {
err = errors.Wrap(err, "Read config file failed.")
return err
}
err = json.Unmarshal(configFile, &conf)
if err != nil {
err = errors.Wrap(err, "Unmarshal config file failed.")
return err
}
return nil
}
func GetConfig() Config {
return conf
}我們當然不止這么一點配置,我們還有數據庫、緩存等配置沒有添加,但不急,我們先理出一個路線,之后的配置可以依葫蘆畫瓢。
好,日志和配置的初始化大致寫好了,我們回過頭來看一下入口文件的調整:
package main
import (
"flag"
"fmt"
"github.com/TomatoMr/awesomeframework/config"
"github.com/TomatoMr/awesomeframework/logger"
"os"
)
func main() {
var configPath string
flag.StringVar(&configPath, "config", "", "配置文件路徑")
flag.Parse()
if configPath == "" {
fmt.Printf("Config Path must be assigned.")
os.Exit(1)
}
var err error
err = config.InitConfig(configPath)
if err != nil {
fmt.Printf("Init config failed. Error is %v", err)
os.Exit(1)
}
logConfig := config.GetConfig().LogConfig
err = logger.InitLogger(logConfig.LogPath, logConfig.LogLevel)
if err != nil {
fmt.Printf("Init logger failed. Error is %v", err)
os.Exit(1)
}
logger.GetLogger().Info("Init success.")
}我們調整了入口文件,從命令行里獲取配置文件路徑,之后初始化了配置和日志,最后打印初始化結果。
首先,編譯一下:
$ go build 接著修改一下你的config.json文件的log_path,然后在命令行指定一下你的配置文件路徑:
$ awesomeframework --config={$your_path}/config.json最后,來看一下運行正不正常,日志文件的打印如下:
2020-01-19T20:41:57.506+0800 info Init success.看完上述內容,你們掌握搭建golang框架的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。