日志用于记录程序的运行情况。当程序出现问题时,第一时间会查看日志进行排查,通过异常信息快速定位问题。今天就写一个同步阻塞日志库,下面是我认为一个日志库应该要有的最基本的功能:
- 日志输出到文件或标准输出。日志输出到文件是为了在
非调试环境中出问题时能够获取到日志信息。 - 输出到文件达到设置大小重写。避免日志文件过大占用空间。
- 支持日志级别。因为打印日志会占用很多cpu资源,在
非调试环境中运行,需要设置较高的日志级别。 - 线程安全。避免日志错乱。
- 同步阻塞。异步写日志可能造成日志丢失,不利于排查问题。
- 完善的日志排查信息:时间,文件名,函数名,行号等。有利于快速定位打印日志的地方。
今天就不贴实现代码了,代码也是比较简单的,完整的代码。看一下test代码和效果:
func Test_logger(t *testing.T) {
// SetFilepath("/tmp/logger.log");
SetSize(1024)
SetLevel(LEVEL_ALL)
Traceln("hello", " world")
Tracef("%s - %s", "hello", "world")
Debugln("hello", " world")
Debugf("%s - %s", "hello", "world")
Infoln("hello", " world")
Infof("%s - %s", "hello", "world")
Warnln("hello", " world")
Warnf("%s - %s", "hello", "world")
Errorln("hello", " world")
Errorf("%s - %s", "hello", "world")
Fatalln("hello", " world")
Fatalf("%s - %s", "hello", "world")
}
输出:
[T][2020/04/13/17:12:16][logger_test.go/Test_logger:14]: hello world
[T][2020/04/13/17:12:16][logger_test.go/Test_logger:15]: hello - world
[D][2020/04/13/17:12:16][logger_test.go/Test_logger:16]: hello world
[D][2020/04/13/17:12:16][logger_test.go/Test_logger:17]: hello - world
[I][2020/04/13/17:12:16][logger_test.go/Test_logger:18]: hello world
[I][2020/04/13/17:12:16][logger_test.go/Test_logger:19]: hello - world
[W][2020/04/13/17:12:16][logger_test.go/Test_logger:20]: hello world
[W][2020/04/13/17:12:16][logger_test.go/Test_logger:21]: hello - world
[E][2020/04/13/17:12:16][logger_test.go/Test_logger:22]: hello world
[E][2020/04/13/17:12:16][logger_test.go/Test_logger:23]: hello - world
[F][2020/04/13/17:12:16][logger_test.go/Test_logger:24]: hello world
[F][2020/04/13/17:12:16][logger_test.go/Test_logger:25]: hello - world