可变参数列表的使用:修改prinft使之可以自己控制打印等级

定制打印函数

Posted by 雯饰太一 on May 28, 2023

可变参数列表的使用:修改prinft使之可以自己控制打印等级

头文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma once
#include <stdio.h>
#include <stdarg.h>

enum NotifyLevel {
	NL_ALWAYS = 1 << 0,
	NL_FATAL = 1 << 1,
	NL_WARN = 1 << 2,
	NL_NOTICE = 1 << 3,
	NL_INFO = 1 << 4,
	NL_DEBUG_INFO = 1 << 5,
	NL_DEBUG_FP = 1 << 6,
	NL_ALL = NL_ALWAYS | NL_FATAL | NL_WARN | NL_NOTICE | NL_INFO | NL_DEBUG_INFO | NL_DEBUG_FP
};

void local_set_notify_severity(const NotifyLevel& ns);
void local_printf(const char* format, ...);
void local_printf_ex(const NotifyLevel& ns, const char* format, ...);

源文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "LocalPrintf.h"

NotifyLevel NS_Default = NL_ALL;

void local_set_notify_severity(const NotifyLevel& ns)
{
	NS_Default = ns;
}

void local_printf(const char* format, ...)
{
	char fm_buffer[512];
	int fm_len = 0;
	va_list ap;
	va_start(ap, format);
	fm_len = vsnprintf(fm_buffer, 512, format, ap);
	va_end(ap);
	printf("%s", fm_buffer);
}

bool level_check(const NotifyLevel& ns, const NotifyLevel& dns, char* pre)
{
	if (ns & dns)
	{
		printf(pre);
		return true;
	}
	return false;
}

void local_printf_ex(const NotifyLevel& ns, const char* format, ...)
{
	int iHit = 0;
	if ((iHit <= 1) && level_check(ns, NL_ALWAYS, "[ALWAYS]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_FATAL, "[FATAL]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_WARN, "[WARN]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_NOTICE, "[NOTICE]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_INFO, "[INFO]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_DEBUG_INFO, "[DEBUG_INFO]")) iHit++;
	if ((iHit <= 1) && level_check(ns, NL_DEBUG_FP, "[DEBUG_FP]")) iHit++;

	if (iHit < 1) return;

	char fm_buffer[512];
	int fm_len = 0;
	va_list ap;
	va_start(ap, format);
	fm_len = vsnprintf(fm_buffer, 512, format, ap);
	va_end(ap);
	printf("%s", fm_buffer);
}

注:主要是va_系列函数的使用。上述代码不能输出太长的字符串,需要限制到512字节内才行,后续会更新更强的日志输出