summaryrefslogtreecommitdiff
path: root/src/syncevo/Logging.cpp
blob: 82a063a529c140c6c63280f0187f39ae02a76258 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
 * Copyright (C) 2009 Patrick Ohly <patrick.ohly@gmx.de>
 * Copyright (C) 2009 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include <syncevo/Logging.h>
#include <syncevo/LogStdout.h>

#include <vector>
#include <string.h>

#include <syncevo/declarations.h>
SE_BEGIN_CXX

std::string Logger::m_processName;

Logger::Logger() :
    m_level(INFO)
{
}

Logger::~Logger()
{
}

static std::vector<Logger *> &loggers()
{
    // allocate array once and never free it because it might be needed till
    // the very end of the application life cycle
    static std::vector<Logger *> *loggers = new std::vector<Logger *>;
    return *loggers;
}

Logger &Logger::instance()
{
    // prevent destructing this instance as part of the executable's
    // shutdown by allocating it dynamically, because it may be
    // needed by other instances that get destructed later
    // (order of global instance construction/destruction is
    // undefined)
    static LoggerStdout *DefaultLogger = new LoggerStdout;
    if (!loggers().empty()) {
        return *loggers()[loggers().size() - 1];
    } else {
        return *DefaultLogger;
    }
}

void Logger::pushLogger(Logger *logger)
{
    loggers().push_back(logger);
}

void Logger::popLogger()
{
    if (loggers().empty()) {
        throw "too many popLogger() calls";
    } else {
        loggers().pop_back();
    }
}

int Logger::numLoggers()
{
    return (int)loggers().size();
}

Logger *Logger::loggerAt(int index)
{
    return index < 0 || index >= (int)loggers().size() ?
        NULL :
        loggers()[index];
}

void Logger::formatLines(Level msglevel,
                             Level outputlevel,
                             const std::string *processName,
                             const std::string *prefix,
                             const char *format,
                             va_list args,
                             boost::function<void (std::string &buffer, size_t expectedTotal)> print)
{
    std::string tag;

    // in case of 'SHOW' level, don't print level and prefix information
    if (msglevel != SHOW) {
        std::string reltime;
        std::string procname;
        const std::string *realProcname;

        if (processName) {
            realProcname = processName;
        } else {
            realProcname = &m_processName;
        }
        if (!realProcname->empty()) {
            procname.reserve(realProcname->size() + 1);
            procname += " ";
            procname += *realProcname;
        }

        if (outputlevel >= DEBUG) {
            // add relative time stamp
            Timespec now = Timespec::monotonic();
            if (!m_startTime) {
                // first message, start counting time
                m_startTime = now;
                time_t nowt = time(NULL);
                struct tm tm_gm, tm_local;
                char buffer[2][80];
                gmtime_r(&nowt, &tm_gm);
                localtime_r(&nowt, &tm_local);
                reltime = " 00:00:00";
                strftime(buffer[0], sizeof(buffer[0]),
                         "%a %Y-%m-%d %H:%M:%S",
                         &tm_gm);
                strftime(buffer[1], sizeof(buffer[1]),
                         "%H:%M %z %Z",
                         &tm_local);
                std::string line =
                    StringPrintf("[DEBUG%s%s] %s UTC = %s\n",
                                 procname.c_str(),
                                 reltime.c_str(),
                                 buffer[0],
                                 buffer[1]);
                print(line, 1);
            } else {
                if (now >= m_startTime) {
                    Timespec delta = now - m_startTime;
                    reltime = StringPrintf(" %02ld:%02ld:%02ld",
                                           delta.tv_sec / (60 * 60),
                                           (delta.tv_sec % (60 * 60)) / 60,
                                           delta.tv_sec % 60);
                } else {
                    reltime = " ??:??:??";
                }
            }
        }
        tag = StringPrintf("[%s%s%s] %s%s",
                           levelToStr(msglevel),
                           procname.c_str(),
                           reltime.c_str(),
                           prefix ? prefix->c_str() : "",
                           prefix ? ": " : "");
    }

    std::string output = StringPrintfV(format, args);

    if (!tag.empty()) {
        // Print individual lines.
        //
        // Total size is guessed by assuming an average line length of
        // around 40 characters to predict number of lines.
        size_t expectedTotal = (output.size() / 40 + 1) * tag.size() + output.size();
        size_t pos = 0;
        while (true) {
            size_t next = output.find('\n', pos);
            if (next != output.npos) {
                std::string line;
                line.reserve(tag.size() + next + 1 - pos);
                line.append(tag);
                line.append(output, pos, next + 1 - pos);
                print(line, expectedTotal);
                pos = next + 1;
            } else {
                break;
            }
        }
        if (pos < output.size() || output.empty()) {
            // handle dangling last line or empty chunk (don't
            // want empty line for that, print at least the tag)
            std::string line;
            line.reserve(tag.size() + output.size() - pos + 1);
            line.append(tag);
            line.append(output, pos, output.size() - pos);
            line += '\n';
            print(line, expectedTotal);
        }
    } else {
        if (!boost::ends_with(output, "\n")) {
            // append newline if necessary
            output += '\n';
        }
        print(output, 0);
    }
}

Logger::MessageOptions::MessageOptions(Level level) :
    m_level(level),
    m_prefix(NULL),
    m_file(NULL),
    m_line(0),
    m_function(NULL),
    m_processName(NULL)
{
}

Logger::MessageOptions::MessageOptions(Level level,
                                       const std::string *prefix,
                                       const char *file,
                                       int line,
                                       const char *function) :
    m_level(level),
    m_prefix(prefix),
    m_file(file),
    m_line(line),
    m_function(function),
    m_processName(NULL)
{
}

void Logger::message(Level level,
                     const std::string *prefix,
                     const char *file,
                     int line,
                     const char *function,
                     const char *format,
                     ...)
{
    va_list args;
    va_start(args, format);
    messagev(MessageOptions(level, prefix, file, line, function), format, args);
    va_end(args);
}

void Logger::message(Level level,
                     const std::string &prefix,
                     const char *file,
                     int line,
                     const char *function,
                     const char *format,
                     ...)
{
    va_list args;
    va_start(args, format);
    messagev(MessageOptions(level, &prefix, file, line, function), format, args);
    va_end(args);
}

void Logger::messageWithOptions(const MessageOptions &options,
                                const char *format,
                                ...)
{
    va_list args;
    va_start(args, format);
    messagev(options, format, args);
    va_end(args);
}

const char *Logger::levelToStr(Level level)
{
    switch (level) {
    case SHOW: return "SHOW";
    case ERROR: return "ERROR";
    case WARNING: return "WARNING";
    case INFO: return "INFO";
    case DEV: return "DEVELOPER";
    case DEBUG: return "DEBUG";
    default: return "???";
    }
}

Logger::Level Logger::strToLevel(const char *str)
{
    // order is based on a rough estimate of message frequency of the
    // corresponding type
    if (!str || !strcmp(str, "DEBUG")) {
        return DEBUG;
    } else if (!strcmp(str, "INFO")) {
        return INFO;
    } else if (!strcmp(str, "SHOW")) {
        return SHOW;
    } else if (!strcmp(str, "ERROR")) {
        return ERROR;
    } else if (!strcmp(str, "WARNING")) {
        return WARNING;
    } else if (!strcmp(str, "DEV")) {
        return DEV;
    } else {
        return DEBUG;
    }
}

#ifdef HAVE_GLIB
void Logger::glogFunc(const gchar *logDomain,
                      GLogLevelFlags logLevel,
                      const gchar *message,
                      gpointer userData)
{
    Logger::instance().message((logLevel & (G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL)) ? ERROR :
                               (logLevel & G_LOG_LEVEL_WARNING) ? WARNING :
                               (logLevel & (G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO)) ? SHOW :
                               DEBUG,
                               NULL,
                               NULL,
                               0,
                               NULL,
                               "%s%s%s",
                               logDomain ? logDomain : "",
                               logDomain ? ": " : "",
                               message);
}

#endif

int Logger::sysyncPrintf(FILE *stream,
                         const char *format,
                         ...)
{
    va_list args;
    va_start(args, format);
    static const std::string prefix("SYSYNC");
    if (boost::starts_with(format, prefix) &&
        format[prefix.size()] == ' ') {
        // Skip initial "SYSYNC " prefix, because it will get re-added
        // in a better way (= to each line) via the prefix parameter.
        format += prefix.size() + 1;
    }
    Logger::instance().messagev(MessageOptions(DEBUG, &prefix, NULL, 0, NULL), format, args);
    va_end(args);

    return 0;
}

SE_END_CXX