c++ 打印封装 每次打印前面加上时间戳

c++ 打印封装 每次打印前面加上时间戳,封装之后我们打印不必每次都加上时间。

#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <mutex>
#include <pthread.h>
#include <thread> 
#include <unistd.h> 
std::mutex g_mtx;
void printfTime()
{
    char buf[32] = {0};
	struct timeval tv;
	struct tm      tm;
	size_t         len = 28;
	memset(&tv, 0, sizeof(tv));
	memset(&tm, 0, sizeof(tm));
	gettimeofday(&tv, NULL);
	localtime_r(&tv.tv_sec, &tm);
	strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm);
	len = strlen(buf);
	sprintf(buf + len, ".%-6.3d", (int)(tv.tv_usec/1000)); 
    printf("%s",buf);
}
void printXX()
{
    std::cout<<std::endl;
}

template <typename T,typename... types>

void printXX(const T& firstArg,const types&... arges)
{
    std::cout<<firstArg;
    printXX(arges...);
}
template <typename T,typename... types>

void mvPrintf(const T& firstArg,const types&... arges)
{
    std::lock_guard<std::mutex> lock(g_mtx);
    printfTime();
    printXX(firstArg,arges...);
}

int main()
{   
    int i = 0;
    std::string a="ddddd";
    mvPrintf("i = ", i, " a = ",a);
    i = 1000;
    mvPrintf("i = ", i, " a = ",a);
    mvPrintf("ssssssssssssssssssssssssssssssss ");
    return 0;
}

输出:

 


版权声明:本文为weixin_40026739原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。