1 /**
2 * Copyright (C) ARM Limited 2010-2013. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <stdarg.h>
12 #include <string.h>
14 #ifdef WIN32
15 #define MUTEX_INIT() mLoggingMutex = CreateMutex(NULL, false, NULL);
16 #define MUTEX_LOCK() WaitForSingleObject(mLoggingMutex, 0xFFFFFFFF);
17 #define MUTEX_UNLOCK() ReleaseMutex(mLoggingMutex);
18 #define snprintf _snprintf
19 #else
20 #include <pthread.h>
21 #define MUTEX_INIT() pthread_mutex_init(&mLoggingMutex, NULL)
22 #define MUTEX_LOCK() pthread_mutex_lock(&mLoggingMutex)
23 #define MUTEX_UNLOCK() pthread_mutex_unlock(&mLoggingMutex)
24 #endif
26 #include "Logging.h"
28 // Global thread-safe logging
29 Logging* logg = NULL;
31 Logging::Logging(bool debug) {
32 mDebug = debug;
33 MUTEX_INIT();
35 strcpy(mErrBuf, "Unknown Error");
36 strcpy(mLogBuf, "Unknown Message");
37 }
39 Logging::~Logging() {
40 }
42 void Logging::logError(const char* file, int line, const char* fmt, ...) {
43 va_list args;
45 MUTEX_LOCK();
46 if (mDebug) {
47 snprintf(mErrBuf, sizeof(mErrBuf), "ERROR[%s:%d]: ", file, line);
48 } else {
49 mErrBuf[0] = 0;
50 }
52 va_start(args, fmt);
53 vsnprintf(mErrBuf + strlen(mErrBuf), sizeof(mErrBuf) - 2 - strlen(mErrBuf), fmt, args); // subtract 2 for \n and \0
54 va_end(args);
56 if (strlen(mErrBuf) > 0) {
57 strcat(mErrBuf, "\n");
58 }
59 MUTEX_UNLOCK();
60 }
62 void Logging::logMessage(const char* fmt, ...) {
63 if (mDebug) {
64 va_list args;
66 MUTEX_LOCK();
67 strcpy(mLogBuf, "INFO: ");
69 va_start(args, fmt);
70 vsnprintf(mLogBuf + strlen(mLogBuf), sizeof(mLogBuf) - 2 - strlen(mLogBuf), fmt, args); // subtract 2 for \n and \0
71 va_end(args);
72 strcat(mLogBuf, "\n");
74 fprintf(stdout, "%s", mLogBuf);
75 fflush(stdout);
76 MUTEX_UNLOCK();
77 }
78 }