日志输出
将调试信息写入日志
/* 日志记录 */
void WriteMsgToLog(LPCTSTR Msg) {
FILE* file = NULL;
fopen_s(&file, LOGFILE, "a+");
if (!file || !Msg) {
return;
}
fprintf_s(file, "%s\n", Msg);
fflush(file);
fclose(file);
file = NULL;
return;
}
示例:
WriteMsgToLog("Msg...");
将调试信息和值写入日志
/* 输出值和消息到日志记录 */
void WriteValueAndMsgToLog(DWORD dwValue, LPCTSTR MsgInfo) {
if (!MsgInfo) return;
TCHAR Msg[128] = { 0 };
sprintf_s(Msg, "%s %lu", MsgInfo, dwValue);
WriteMsgToLog(Msg);
}
示例:
DWORD dwError = GetLastError();
WriteValueAndMsgToLog(dwError, "Msg...");
将错误信息输出到日志
/* 将错误信息输出到日志 并返回错误码 参数为函数名 */
DWORD WriteErrorMsgToLog(LPTSTR lpszFunctionName) {
/* 检索最后一个错误代码的系统错误消息 */
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dwError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)& lpMsgBuf,
0, NULL);
/* 显示错误消息 */
/* 输出到MessageBox */
/*lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunctionName) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunctionName, dwError, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);*/
/* 输出到日志 */
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunctionName) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("[Error] %s failed with error %d: %s"),
lpszFunctionName, dwError, lpMsgBuf);
WriteMsgToLog((LPCTSTR)lpDisplayBuf);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
return dwError;
}
示例:
WriteErrorMsgToLog(TEXT("Msg..."));
Dbgview输出
输出调试信息到 Dbgview
/* 输出调试信息到 Dbgview */
static void DbgPrintEx(LPCTSTR format, ...) {
LPCTSTR outputString;
PTCHAR buffer = NULL;
size_t length;
va_list argp;
va_start(argp, format);
length = 4096;
buffer = new TCHAR[length]{ 0 };
if (buffer) {
_vsntprintf_s(buffer, length, _TRUNCATE, format, argp);//StringCchPrintf((LPTSTR)buffer,length,format,argp);
outputString = buffer;
OutputDebugString(outputString);
}
if (buffer) {
delete[] buffer;
}
va_end(argp);
}
#define DbgPrint(external_buff) \
TCHAR buff[256] = { 0 };\
StringCchPrintf(buff, 256, _T("DebugInfo(%d)-<%S>: "), __LINE__, __FUNCTION__);\
DbgPrintEx(_T("%s; %s; err:%d; \n"), buff,external_buff, GetLastError())
示例:
DbgPrint("Msg...");