之前有写过:Print debug message based on MinGW 。那是在MinGW的编译环境下输出调试信息到本地文件中。如果换成MSVC的编译环境,原来的方法就行不通了,因为某些函数和语法不支持:
#ifndef LOG_H
#define LOG_H
#include <stdarg.h>
#include <QDebug>
#include <QString>
#include <unistd.h>
#include <stdio.h>
#define DEBUG 1
static QString logFilePath;
void LogInit();
void LOGBASE(const char *file, const int line, const char *funcName, const char * fmt, ...);
#define LOGDBG(fmt,args...) LOGBASE(__FILE__,__LINE__,__FUNCTION__, fmt, ##args)
#endif /* LOG_H_ */
##args
是不被MSVC认识的,另外sprintf,truncate等函数也因为环境的改变而无法正常工作(新的编译器不认识)。
故,需要重新设计实现的细节:
logprinter.h
#ifndef LOGPRINTER_H
#define LOGPRINTER_H
#include <stdarg.h>
#include <QDebug>
#include <stdio.h>
#include <QString>
#include <windows.h>
#include <io.h>
#include <QCoreApplication>
#if _MSC_VER
#define snprintf _snprintf
#endif
static QString logFilePath;
void LogInit();
void print( const char* file, const int line, const char * fmt, ...);
#define printer(...) print( __FILE__, __LINE__, __VA_ARGS__ )
#endif // LOGPRINTER_H
logprinter.cpp
#include "logprinter.h"
#include <stdio.h>
void LogInit()
{
logFilePath = QCoreApplication::applicationDirPath();
logFilePath = logFilePath + "/log.txt";
if( 0 == _access( logFilePath.toStdString().c_str(), 0 ) )
{
_unlink( logFilePath.toStdString().c_str() );
}
}
void print(const char *file, const int line, const char *fmt, ...)
{
const int BUFFSIZE = 1024;
char buffer[ BUFFSIZE ] = {0};
int offset = 0;
FILE *fp = NULL;
offset = snprintf( buffer + offset, BUFFSIZE - offset, "[%s, %d]\n", file, line );
va_list vap;
va_start( vap, fmt ); //variable arguments list vap init
vsnprintf( buffer + offset, BUFFSIZE - offset, fmt, vap ); // add list vap to buff
va_end( vap );
fp = fopen( logFilePath.toStdString().c_str(), "a" );
if( NULL != fp )
{
fprintf( fp, "%s", buffer );
fclose( fp );
}
}
相关应用:
https://github.com/theArcticOcean/CLib/tree/master/MSVCLogprinter