日志用于记录程序的运行情况。当程序出现问题时,第一时间会查看日志进行排查,通过异常信息快速定位问题。今天就写一个同步阻塞日志库,下面是我认为一个日志库应该要有的最基本的功能:
- 日志输出到文件或标准输出。日志输出到文件是为了在
非调试环境中出问题时能够获取到日志信息。 - 输出到文件达到设置大小重写。避免日志文件过大占用空间。
- 支持日志级别。因为打印日志会占用很多cpu资源,在
非调试环境中运行,需要设置较高的日志级别。 - 线程安全。避免日志错乱。
- 同步阻塞。异步写日志可能造成日志丢失,不利于排查问题。
- 完善的日志排查信息:时间,文件名,函数名,行号等。有利于快速定位打印日志的地方。
实现代码比较简单就不贴了,完整代码。下面是实例代码:
#include "logger.h"
int main(void) {
const char *str = "hello";
const char *str2 = "world";
const char *filepath = "/tmp/logger.log";
logger_set_filepath(filepath);
logger_set_size(1024 * 1024);
logger_set_level(LOGGER_LV_ALL);
_TRACE_LOG("%s %s", str, str2);
_DEBUG_LOG("%s %s", str, str2);
_INFO_LOG("%s %s", str, str2);
_WARN_LOG("%s %s", str, str2);
_ERROR_LOG("%s %s", str, str2);
_FATAL_LOG("%s %s", str, str2);
}
输出:
[T] [Apr 16 16:59:34] [m.c] [main:12]: hello world
[D] [Apr 16 16:59:34] [m.c] [main:13]: hello world
[I] [Apr 16 16:59:34] [m.c] [main:14]: hello world
[W] [Apr 16 16:59:34] [m.c] [main:15]: hello world
[E] [Apr 16 16:59:34] [m.c] [main:16]: hello world
[F] [Apr 16 16:59:34] [m.c] [main:17]: hello world