现在的位置: 首页 > 综合 > 正文

log日志:简单的log日志输出(C++)

2018年10月03日 ⁄ 综合 ⁄ 共 1107字 ⁄ 字号 评论关闭

一、头文件types.h

////////////////////////////////////////////////////////////////
//
//Descript: common definition and function.
//  Author: guowemyan
//    Date:2013.12.17
//
////////////////////////////////////////////////////////////////
#ifndef _TYPES_H_
#define _TYPES_H_


#include <string>
#include <iostream>


#define LOG_DEBUG(msg) cout<<msg<<"("<<__FILE__<<":"<<__LINE__<<")"<<endl;

std::string mformat(const char *fmt, ...);


#endif //_TYPES_H_

二、实现文件types.cpp

////////////////////////////////////////////////////////////////
//
//Descript: common definition and function.
//  Author: guowemyan
//    Date:2013.12.17
//
////////////////////////////////////////////////////////////////
#include "types.h"

#include <stdarg.h>

using namespace std;

string mformat(const char *fmt, ...)
{
	size_t size = 1024;
	char* buf = new char[size];
	while(1)
	{
		va_list args;
		int n;

		va_start(args, fmt);
		n = vsprintf(buf, fmt, args);
		va_end(args);

		if ((n > -1) && (static_cast<size_t>(n) < size)) 
		{
			std::string s(buf);
			delete [] buf;
			return s;
		}
		// Else try again with more space.
		size = (n > -1) ?
			n + 1 :   // ISO/IEC 9899:1999
		size * 2; // twice the old size

		delete [] buf;
		buf = new char[size];
	}

}

三、调用方式

if ( len <= 0 )
	{
		LOG_DEBUG(mformat("len <= 0, len: %d. ", len));
		return -1;
	}

抱歉!评论已关闭.