go開發屬於本身的日誌庫-日誌庫易用性封裝

文件日誌和console日誌也完成了,咱們試試在其餘其餘使用一下。在咱們以前的server中,main.go輸入一下代碼:函數

package main

import "hm_log"

var log hm_log.Log

func initLog(logPath, logName string) {
    //log := hm_log.NewFileLog(logPath, logName)
    log := hm_log.NewConsoleLog()
    log.Debug("this is debug")
}

func Run() {
    log.Warn("this is warn")
}

func main() {
    initLog(".", "server")
    Run()
}

複製代碼

運行這個程序,能夠看到終端成功的輸入了日誌,而後試試文件日誌庫。 可是這樣有一個麻煩就是,每一個相關都須要聲明一個log,仍是麻煩,因此咱們須要進行提煉,將log 全局變量封裝到咱們的日誌庫中,只給一個初始函數,使用的時候直接log變量便可。進入咱們的hm_log項目中,新建一個log.goui

package hm_log

import "fmt"

var log Log

func InitLog(name string, config map[string]string) (err error) {
	switch name {
	case "file":
		log, err = NewFileLog(config)
	case "console":
		log, err = NewConsoleLog()
	default:
		err = fmt.Errorf("unspport log name:%s", name)
	}
	return
}

func Debug(format string, args ...interface{}) {
	log.Debug(format, args...)
}

func Trace(format string, args ...interface{}) {
	log.Trace(format, args...)
}

func Info(format string, args ...interface{}) {
	log.Info(format, args...)
}

func Warn(format string, args ...interface{}) {
	log.Warn(format, args...)
}

func Error(format string, args ...interface{}) {
	log.Error(format, args...)
}

func Fatal(format string, args ...interface{}) {
	log.Fatal(format, args...)
}

func Close() {
	log.Close()
}
複製代碼

因爲文件日誌須要配置多個參數,這是咱們直接使用map來進行傳參便可。由於傳的是map,因此咱們的文件日誌庫file.go也須要進行修改:this

func NewFileLog(config map[string]string) (logFile Log, err error) {
   //判斷是否傳入了值,沒有值就拋出錯誤
	logPath, ok := config["log_path"]
	if !ok {
		err = fmt.Errorf("not found log_path")
		return
	}
	logName, ok := config["log_name"]
	if !ok {
		err = fmt.Errorf("not found log_name")
		return
	}

	logFile = &FileLog{
		logPath:       logPath,
		logName:       logName,
	}

	//logFile.init()
	logFile.Init()
	return
}
複製代碼

logFile.init()這裏是會報錯的,由於FileLog沒有這個方法,因此文們須要加上一個init()方法。進入log_interface.go:spa

package hm_log

type Log interface {
	Debug(format string, args ...interface{}) // ...表示接收可變參數
	Trace(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
	Fatal(format string, args ...interface{})
	Close() // 文件須要進行關閉操做
	Init()
}
複製代碼

把咱們以前的file.go,console.go給加上Init(): file.godebug

// 替換以前的init()
func (f *FileLog) Init() {
}
複製代碼

console.go日誌

func (f *FileLog) Init() { }
複製代碼

咱們再來修改以前的main.go:code

package main

import "hm_log"

func initLog(logPath, logName string) {
   //log := hm_log.NewFileLog(logPath, logName)
	config := make(map[string]string, 8)
	config["log_path"] = "."
	config["log_name"] = "server"
    
   err := InitLog("file", config)
	 if err != nil {
		 return
	 }
}

func Run() {
    log.Warn("this is warn")
}

func main() {
    initLog(".", "server")
    Run()
}
複製代碼

這樣咱們就不須要聲明全局變量log,使用起來就很方便了。運行一個,能夠正常的使用。orm

相關文章
相關標籤/搜索