利用接口实现简单的日志写入器

logger.go

package main

//声明日志写入器接口
type LogWriter interface {
	Write(data interface{}) error
}

type Logger struct {
	writerList []LogWriter
}
//注册写入器,将多个writer方法存到切片中
func (l *Logger) RegisterWriter(writer LogWriter) {
	l.writerList = append(l.writerList, writer)
}
//数据写入日志
func (l *Logger) Log(data interface{}) {
	for _, writer := range l.writerList{
		writer.Write(data)
	}
}
//创建日志器的实例
func NewLogger() *Logger {
	return &Logger{}
}

file.go

package main

import (
	"errors"
	"fmt"
	"os"
)

type fileWriter struct {
	file *os.File
}
//创建文件
func (f *fileWriter) SetFile(filename string) (err error) {
	if f.file != nil {
		f.file.Close()
	}

	f.file, err = os.Create(filename)
	return err
}
//实现接口
func (f *fileWriter) Write(data interface{}) error {
	if f.file == nil {
		return errors.New("file not created")
	}

	str := fmt.Sprintf("%v\n", data)

	_, err := f.file.Write([]byte(str))
	return err
}
//创建文件写入器实例
func newFileWriter() *fileWriter{
	return &fileWriter{}
}

console.go

package main

import (
	"fmt"
	"os"
)

type consoleWriter struct {

}
//实现LogWriter的writer()方法
func (f *consoleWriter) Write(data interface{}) error {
	str := fmt.Sprintf("%v\n",data)
	_,err := os.Stdout.Write([]byte(str))

	return err
}
//创建consoleWriter实例
func newConsoleWriter() *consoleWriter{
	return &consoleWriter{}
}

main.go

package main

import "fmt"

func createLogger() *Logger{
	l := NewLogger()

	cw := newConsoleWriter()
	l.RegisterWriter(cw)

	fw := newFileWriter()
	if err := fw.SetFile("log.log");err != nil{
		fmt.Println(err)
	}

	l.RegisterWriter(fw)

	return l
}

func main(){
	l := createLogger()
	l.Log("hello")
}

 

你可能感兴趣的:(Go小记)