Merge branch 'linux-3.10.y' of git://git.kernel.org/pub/scm/linux/kernel/git/stable...
[firefly-linux-kernel-4.4.55.git] / tools / gator / daemon / Logging.cpp
1 /**
2  * Copyright (C) ARM Limited 2010-2015. 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  */
8
9 #include "Logging.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <stdarg.h>
14 #include <string.h>
15
16 #ifdef WIN32
17 #define MUTEX_INIT()    mLoggingMutex = CreateMutex(NULL, false, NULL);
18 #define MUTEX_LOCK()    WaitForSingleObject(mLoggingMutex, 0xFFFFFFFF);
19 #define MUTEX_UNLOCK()  ReleaseMutex(mLoggingMutex);
20 #define snprintf _snprintf
21 #else
22 #include <pthread.h>
23 #define MUTEX_INIT()    pthread_mutex_init(&mLoggingMutex, NULL)
24 #define MUTEX_LOCK()    pthread_mutex_lock(&mLoggingMutex)
25 #define MUTEX_UNLOCK()  pthread_mutex_unlock(&mLoggingMutex)
26 #endif
27
28 // Global thread-safe logging
29 Logging* logg = NULL;
30
31 Logging::Logging(bool debug) {
32         mDebug = debug;
33         MUTEX_INIT();
34
35         strcpy(mErrBuf, "Unknown Error");
36         strcpy(mLogBuf, "Unknown Message");
37 }
38
39 Logging::~Logging() {
40 }
41
42 void Logging::_logError(const char *function, const char *file, int line, const char *fmt, ...) {
43         va_list args;
44
45         MUTEX_LOCK();
46         if (mDebug) {
47                 snprintf(mErrBuf, sizeof(mErrBuf), "ERROR: %s(%s:%i): ", function, file, line);
48         } else {
49                 mErrBuf[0] = 0;
50         }
51
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);
55
56         if (strlen(mErrBuf) > 0) {
57                 strcat(mErrBuf, "\n");
58         }
59         MUTEX_UNLOCK();
60 }
61
62 void Logging::_logMessage(const char *function, const char *file, int line, const char *fmt, ...) {
63         if (mDebug) {
64                 va_list args;
65
66                 MUTEX_LOCK();
67                 snprintf(mLogBuf, sizeof(mLogBuf), "INFO: %s(%s:%i): ", function, file, line);
68
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");
73
74                 fprintf(stdout, "%s", mLogBuf);
75                 fflush(stdout);
76                 MUTEX_UNLOCK();
77         }
78 }