其他
分享一个简单且轻量级的日志库:log.c
The following article is from 老吴嵌入式 Author 吴伟东Jack
对于嵌入式底层应用开发,基本离不开日志功能,今天一个开源的 log.c 代码,简单到了开箱即用的级别。
log.c 是什么?
log.c 怎么用?
log_debug(const char *fmt, ...);
log_info(const char *fmt, ...);
log_warn(const char *fmt, ...);
log_error(const char *fmt, ...);
log_fatal(const char *fmt, ...);
int main(int argc, char *argv[])
{
log_set_level(0);
log_set_quiet(0);
FILE *fp1, *fp2;
fp1 = fopen("./log_info.txt", "ab");
if(fp1 == NULL)
return -1;
fp2 = fopen("./log_debug.txt", "ab");
if(fp2 == NULL)
return -1;
log_add_fp(fp1, LOG_INFO);
log_add_fp(fp2, LOG_DEBUG);
log_debug("debug");
log_info("info");
log_warn("warn");
fclose(fp2);
fclose(fp1);
return 0;
}
23:31:05 DEBUG example1.c:20: debug
23:31:05 INFO example1.c:21: info
23:31:05 WARN example1.c:22: warn
$ cat log_debug.txt
2022-05-08 23:31:05 DEBUG example1.c:20: debug
2022-05-08 23:31:05 INFO example1.c:21: info
2022-05-08 23:31:05 WARN example1.c:22: warn
$ cat log_info.txt
2022-05-08 23:31:05 INFO example1.c:21: info
2022-05-08 23:31:05 WARN example1.c:22: warn
pthread_mutex_t MUTEX_LOG;
void log_lock(bool lock, void *udata);
int main()
{
log_set_level(0);
log_set_quiet(0);
pthread_mutex_init(&MUTEX_LOG, NULL);
log_set_lock(log_lock, &MUTEX_LOG);
/* Insert threaded application code here... */
log_info("I'm threadsafe");
pthread_mutex_destroy(&MUTEX_LOG);
return 0;
}
void log_lock(bool lock, void* udata)
{
pthread_mutex_t *LOCK = (pthread_mutex_t*)(udata);
if (lock)
pthread_mutex_lock(LOCK);
else
pthread_mutex_unlock(LOCK);
}
log.c 的内部实现?
总结
https://github.com/armink/EasyLoggerhttps://github.com/HardySimpson/zloghttps://github.com/0xmalloc/c-log
●专栏《嵌入式工具》●专栏《嵌入式开发》●专栏《Keil教程》●嵌入式专栏精选教程