go开发属于自己的日志库-控制台日志实现

上一篇中我们将文件日志库基本实现了,我们现在再讲console日志库实现,那我们的日志库也基本就可以完成了。

新建console.go,把我们console日志库也实现了。因为console日志库只是将日志输出到终端里面。

package hm_log

import (
	"fmt"
	"os"
)

type ConsoleLog struct{}

func NewConsoleLog() (logCon Log, err error) {
	logCon = &ConsoleLog{}
	return
}

func (c *ConsoleLog) Debug(format string, args ...interface{}) {
}

...
func (c *ConsoleLog) Warn(format string, args ...interface{}) {
}
...

func (c *ConsoleLog) Close() {
}
复制代码

但是打印到终端的日志和文件写入的日志是一样,再写一遍也是累,直接将之前的函数写到util.go中,分开调用就可以了:

func writeLog(file *os.File, level int, format string, args... interface{} {
    now := time.Now()
    nowStr := now.Format("2006-01-02 15:04:05.999")
    // 这个数字格式是固定的不能改变的,但是-和:可以更换
    levelStr := LogLevelString(level)
    fileName, funcName, lineNo := GetLineInfo()
    //由于这里返回的是全路径的,但是我们不需要,所以我们只需要文件名以及相关的即可
    fileName = path.Base(fileName)
    funcName = path.Base(funcName)
    msg := fmt.Sprintf(format, args...)
    fmt.Fprintf(file, "%s %s [%s/%s:%d] %s\n", nowStr, levelStr, fileName, funcName, lineNo, msg)
} 
复制代码

file.go

func (f *FileLog) Debug(format string, args ...interface{}) {
    writeLog(f.file, DebugLevel, format, args...)
}
复制代码

console.go

func (c *ConsoleLog) Debug(format string, args ...interface{}) {
    writeLog(os.Stdout, DebugLevel, format, args...)
}
...
func (c *ConsoleLog) Warn(format string, args ...interface{}) {
    writeLog(os.Stdout, WarnLevel, format, args...)
}
...
复制代码

这样我们console日志库就完成了,然后我们来测试一下。 在log_test.go来测试我们写的文件日志库。

package log

import (
    "testing"
)

func TestFileLog(t *testing.T) {
    log := NewFileLog(".", "test")
    log.Debug("this is file debub test")
    log.Warn("this is file warn test")
    log.Close()
}


func TestConsoleLog(t *testing.T) {
    log := NewConsoleLog()
    log.Debug("this is file debub test")
    log.Warn("this is file warn test")
} 

复制代码

go test一下,看看我们终端输出是否和我们之前定义的日志格式一样。

注意

go test 默认执行当前目录下以xxx_test.go的测试文件。 go test -v 可以看到详细的输出信息。 go test -v xxx_test.go 指定测试单个文件,但是该文件中如果调用了其它文件中的模块会报错。 指定某个测试函数运行: go test -v -test.run Testxxx 注意: 该测试会测试包含该函数名的所有函数,即如果待测试的函数名是TestSyncResourceQuota,那么指令go test -v -test.run TestSyncResourceQuota会测试包含该函数名的所有函数(比如TestSyncResourceQuotaSpecChangeTestSyncResourceQuotaSpecHardChange等函数)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值