Skip to content

Instantly share code, notes, and snippets.

@polovik
Last active August 29, 2015 13:57
Show Gist options
  • Save polovik/9617571 to your computer and use it in GitHub Desktop.
Save polovik/9617571 to your computer and use it in GitHub Desktop.
Log in file for Visual Studio
typedef enum {
LOG_INFO = 0, /**< Notification for better debugging */
LOG_WARNING = 1,/**< Incorrect work of application, but it doesn't lead to crash */
LOG_ERROR = 2 /**< Big problem - application is crashed */
} logLevel_e;
static FILE *g_logStream = NULL;
static WCHAR g_logFilePath[MAX_PATH];
static WCHAR g_logMessage[10000];
/** @brief Write to logs messages to file. Also, in debugging, display them in window "Output".
* @param level - criticality level of message.
* @param format - format of logged message.
* @see printf()
*/
void logging(logLevel_e level, WCHAR* format, ...)
{
va_list argptr;
va_start(argptr, format);
_vsnwprintf_s(g_logMessage, ARRAYSIZE(g_logMessage), format, argptr);
va_end(argptr);
OutputDebugString(g_logMessage);
OutputDebugString(L"\n");
if (g_logStream != NULL) {
SYSTEMTIME time;
GetLocalTime(&time);
fwprintf(g_logStream, L"%02d:%02d:%02d.%03d ",
time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
switch (level) {
case LOG_INFO: fwprintf(g_logStream, L"Info: "); break;
case LOG_WARNING: fwprintf(g_logStream, L"Warn: "); break;
case LOG_ERROR: fwprintf(g_logStream, L"Error: "); break;
}
fwprintf(g_logStream, L"%s\n", g_logMessage);
fflush(g_logStream);
}
}
/** @brief Open log file log_autorun.txt in system temporary directory.
*/
void openLogFile()
{
TCHAR tempDirectory[MAX_PATH];
DWORD dwRetVal = 0;
// Gets the temp path env string (no guarantee it's a valid path).
dwRetVal = GetTempPath(MAX_PATH, tempDirectory);
if (dwRetVal > MAX_PATH || (dwRetVal == 0)) {
logging(LOG_ERROR, L"GetTempPath failed");
return;
}
swprintf(g_logFilePath, ARRAYSIZE(g_logFilePath), L"%slog_autorun.txt", tempDirectory);
logging(LOG_INFO, L"Open log file %s", g_logFilePath);
// Open file for writing. Truncate it. Set ability to flush on disk and set encoding - Unicode UTF-8
errno_t err = _wfopen_s(&g_logStream, g_logFilePath, L"wc,ccs=UTF-8");
if (err != 0)
logging(LOG_ERROR, L"Opening log file failed. Error: %d", err);
}
int main(...)
{
openLogFile();
logging(LOG_INFO, L"Start");
...
logging(LOG_INFO, L"Application has been successfully finished");
if (g_logStream != NULL)
fclose(g_logStream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment