오류 로깅 c ++ 사전 처리기 매크로 __line__, __function__
-
05-07-2019 - |
문제
기존 앱에 간단한 오류 로그인을 통합하려고합니다. cout
그래서 나는 <<
운영자. 그러나 선을 기록하고 오류가 발생한 기능을 원하지만 입력하고 싶지는 않습니다. __LINE__, __FUNCTION__
로그인해야 할 때마다. 누구든지 내가 허용하는 데 사용할 수있는 트릭을 알고 있습니까? __LINE__
대신 호출 라인을보고하는 다른 함수 내에서 사용되는 매크로? 그것이 말이되기를 바랍니다.
class myLogClass {
uint8_t level;
public:
bool operator<<( const char * input );
};
bool myLogClass::operator<<( const char * input ) {
logItInSQL( input );
return true;
}
이 대신에 매번
myLogClass << "Line No: " << __LINE__
<< " Function: " << __FUNCTION__
<< " Error: " << "This is my error to be logged";
나는 단지 할 수 있기를 원합니다 :
myLogClass << "This is my error to be logged";
bool myLogClass::operator<<( const char * input ) {
logItInSQL( " Line No: __LINE__" );
logItInSQL( " Function: __FUNCTION__" );
logItInSQL( " Error: " + input );
return true;
}
해결책
myLogClass << "Line No: " << __LINE__ ...
당신과 함께 operator <<
체인은 반환하기 때문에 작동하지 않습니다 bool
.
bool myLogClass::operator << (const char * input)
스트림 삽입을 다음과 같이 정의하는 것이 일반적입니다.
std::ostream& myLogClass::operator << (std::ostream& o, const char * input) {
// do something
return o;
}
이 작업을 수행:
#define log(o, s) o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s // note I leave ; out
또한 매크로를 a do-while
고리:
#define log(o, s) do { o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s; \
} while(0) // here, I leave ; out
그런 다음 행복하게 쓸 수 있습니다.
myLogClass myLogger; // do this
// use it
log(myLogger, "This is my error to be logged"); // note the ;
다른 팁
ANSI C (C ++에서도 작동해야 함)에서 Variadic 함수 및 사전 처리기 매크로를 사용하여 수행 할 수 있습니다. 아래 예를 참조하십시오 :
#include <stdio.h>
#include <stdarg.h>
#define MAXMSIZE 256
#define MyDebug(...) MyInternalDebug(__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__)
void MyInternalDebug( char *file, char *function, const int line, const char *format, ... )
{
char message[MAXMSIZE];
// Variable argument list (VA)
va_list ap;
// Initialize VA
// args : Name of the last named parameter in the function definition.
// The arguments extracted by subsequent calls to va_arg are those after 'args'.
va_start(ap, format);
// Composes a string with the same text that would be printed if 'format' was used on printf,
// but using the elements in the variable argument list identified by 'ap' instead of
// additional function arguments and storing the resulting content as a C string in the buffer pointed by 'message'.
// * The state of arg is likely to be altered by the call.
vsprintf(message, format, ap);
// Custom print function
printf("%s\t%s\t%d\t%s\n",file, function, line, message);
// Finzalize use of VA
va_end(ap);
}
int main ()
{
MyInternalDebug(__FILE__, __FUNCTION__, __LINE__, "An error occured with message = '%s'", "Stack Overflow");
MyDebug("Another error occured with code = %d", 666);
return 0;
}
아니요, 이것이 로깅이 매크로로 수행되는 이유입니다. __LINE__
공통 벌목 함수가 아닌 문제의 라인에서 전처리 기에 의해 확장해야합니다.
Adam Mitz가 언급했듯이 전화 대신 __line__를 사용해야합니다.
"추가 인치"와 같은 추가 매개 변수를 추가하고 __line__ 및 __function__를 사용 하여이 "추가 인력"을 생성하는 매크로를 작성하는 것이 좋습니다.
컴파일에 대한 첫 번째 답변에서 코드를 얻을 수 없었습니다. 작업을 잘 수행하는이 간단한 매크로를 사용합니다.
#define qlog(s) std::cerr << __FUNCTION__ << "::" << __LINE__ << "\t" << s << endl