当前位置:网站首页>Code debugging - print log output to file

Code debugging - print log output to file

2022-06-12 13:31:00 Boring ah le

1、 Output log to file function

void logprintf(const char *fmt, ...)// Custom variable parameter function 
{
    
	static int bLogFirstOpen = 0;  // Static local variables defined in the function body , Its lifetime is the same as that of the global variable , Keep it throughout the program ;
	                                // Its visibility is the same as that of local variables , Only inside this function can this variable be accessed through this variable name .
									
	static char* Log_file = "./libskf_log.txt";// Log file name 
	
	char message[MAX_LOG_SIZE];
	memset(message, 0, MAX_LOG_SIZE);
	//  current time . 
	time_t timer = time(NULL);
	strftime(message, 23, "[%Y-%m-%d %H:%M:%S] ", localtime(&timer));// Current error time 
	
	va_list args;
	va_start(args, fmt);// The first parameter : Variable parameter list   the second : The type of variable parameter 、 Number and order 
	vsnprintf(message + 22, MAX_LOG_SIZE - 22, fmt, args);
	va_end(args);
	FILE * fd = 0;	
	if (bLogFirstOpen == 0)
	{
    
		fd = fopen(Log_file, "wt+");	
		bLogFirstOpen = 1;
	}
	else
	{
    
		fd = fopen(Log_file, "at+");		
	}
	size_t  len = strlen(message);
	fwrite(message, 1, len, fd);
	fclose(fd);

}

2、 usage
rv = SKF_MacFinal(hMac, encdata, &enclen);
if (rv != SAR_OK)
{
    
	logprintf("SKF_MacFinal ERROR, errno[0x%08x]\n", rv);// Output error log to file 
	return -1;
}
原网站

版权声明
本文为[Boring ah le]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010516316658.html