基本要求是
1.线程安全
2.支持分级过滤
3.记录时间,线程id,开始记录头等等
4.跨平台
5.支持回调处理
代码是考虑过跨平台的,主要是锁跟几个函数,有需要改动的地方应该很少,但目前还没做,因为要浪费时间测试呢,往后有需要再改改就是了。
废话不多说上代码
头文件
/*
* CREATE: tifentan
* DATE: 2017/10/30
* MODIFY: 2017/10/30
* NOTE:
* trace.h
*
*
*/
#ifndef TTF_TRACE_H_
#define TTF_TRACE_H_
#include <string>
enum TtfTraceLevel
{
ttfTraceNone = 0x0000, // no trace
ttfTraceStateInfo = 0x0001,
ttfTraceWarning = 0x0002,
ttfTraceError = 0x0004,
ttfTraceCritical = 0x0008,
ttfTraceApiCall = 0x0010,
ttfTraceModuleCall = 0x0020,
ttfTraceInfo = 0x0040,
ttfTraceDebugFlag = 0x007f,
ttfTraceDebug = 0x0080,
ttfTraceDefault = 0x00ff,
ttfTraceMemory = 0x0100, // memory info
ttfTraceTimer = 0x0200, // timing info
ttfTraceStream = 0x0400, // "continuous" stream of data
// Non-verbose level used by LS_INFO of logging.h. Do not use directly.
ttfTraceTerseInfo = 0x2000,
ttfTraceAll = 0xffff
};
enum TtfTraceMode {
ttfTraceModeNone,
ttfTraceModeEnd = 0x0ffff,
};
// External Trace API
class TtfTraceCallback {
public:
virtual void Print(TtfTraceLevel level, const char* message, int length) = 0;
protected:
virtual ~TtfTraceCallback() {}
TtfTraceCallback() {}
};
#define TTF_TRACE_MAX_MESSAGE_SIZE 1024
#define TTF_TRACE_MAX_FILE_SIZE 100000000 //100m
class TtfTrace {
public:
TtfTrace();
~TtfTrace();
int SetFile(char* path);
int SetCallBack(TtfTraceCallback* cb);
int SetFilter(unsigned int filter);
unsigned int GetFilter();
int doTrace(const TtfTraceLevel level,
const char msg[TTF_TRACE_MAX_MESSAGE_SIZE],
const TtfTraceMode module = ttfTraceModeNone,
const int32_t id = 0);
int doTraceEx(const TtfTraceLevel level,
const TtfTraceMode module,
const int32_t id,
char* str,
...);
int Flush();
int Rewind();
unsigned int GetSize();
protected:
int AddThreadId(char* ptr);
int AddTime(char* ptr);
int AddHead(char* ptr);
int AddLevel(char* ptr, TtfTraceLevel level);
int AddModuleAndId(char* ptr, TtfTraceMode module,int32_t id);
int WriteToFile();
private:
TtfTraceCallback *cb_;
CRITICAL_SECTION crit_;
std::string trace_file_path_;
FILE* file_ = nullptr;
size_t position_ = 0;
unsigned int level_filter_ = ttfTraceDefault;
//unsigned int prev_tick_count_ = 0;
char* msg_ = 0;
int msg_len_ = 0;