#include #include #define LOG_BUFFER 512 #define LOG_PREFIX "Application1" #define PATH_APPLICATION "C:\\Temp" int Logging_LogSystem(char *szLogFormat, ...); int main() { Logging_LogSystem("This function can be called in a similar fashion to %s.\r\n", "printf()"); Logging_LogSystem("It's handy for capturing application log or error data (which includes numbers like %d).\r\n", 5); Logging_LogSystem("Using a log buffer size of 0x%X bytes.\r\n", LOG_BUFFER); return 0; } int Logging_LogSystem(char *szLogFormat, ...) { SYSTEMTIME sTime; HANDLE hLogFile = NULL; DWORD dwLength = 0; char szLogString[LOG_BUFFER], szFileName[MAX_PATH], szDateTime[LOG_BUFFER], szErrorString[LOG_BUFFER]; char *szVarList; int iRetVal = TRUE; va_start(szVarList, szLogFormat); if (_vsnprintf_s(szLogString, sizeof(szLogString), _TRUNCATE, szLogFormat, szVarList) == -1) szLogString[sizeof(szLogString) - 1] = '\0'; va_end(szVarList); GetLocalTime(&sTime); sprintf_s(szFileName, sizeof(szFileName), "%s\\Logs\\%s-%04d%02d%02d.Log", PATH_APPLICATION, LOG_PREFIX, sTime.wYear, sTime.wMonth, sTime.wDay); hLogFile = CreateFile(szFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hLogFile != INVALID_HANDLE_VALUE) { if (SetFilePointer(hLogFile, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER) { sprintf_s(szErrorString, sizeof(szErrorString), "Error: %s() - %s() - %d\r\n", __FUNCTION__, "SetFilePointer", GetLastError()); iRetVal = FALSE; goto Error; } sprintf_s(szDateTime, sizeof(szDateTime), "%02d:%02d:%02d ", sTime.wHour, sTime.wMinute, sTime.wSecond); if (!WriteFile(hLogFile, szDateTime, (int) strlen(szDateTime), &dwLength, NULL)) { sprintf_s(szErrorString, sizeof(szErrorString), "Error: %s() - %s() - %d\r\n", __FUNCTION__, "WriteFile", GetLastError()); iRetVal = FALSE; goto Error; } if (!WriteFile(hLogFile, szLogString, (int) strlen(szLogString), &dwLength, NULL)) { sprintf_s(szErrorString, sizeof(szErrorString), "Error: %s() - %s() - %d\r\n", __FUNCTION__, "WriteFile", GetLastError()); iRetVal = FALSE; goto Error; } } else { sprintf_s(szErrorString, sizeof(szErrorString), "Error: %s() - %s() - %d\r\n", __FUNCTION__, "CreateFile", GetLastError()); iRetVal = FALSE; goto Error; } goto Cleanup; Error: // Use alternate log for error condition (Syslog, Event Log etc) // Error captured in szErrorString printf(szErrorString); Cleanup: if (hLogFile) CloseHandle(hLogFile); return iRetVal; }