aboutsummaryrefslogtreecommitdiffstats
path: root/src/geniviextras/qdltregistration.cpp
blob: 47abe21bfd3521e3ad0a3a432011c8ef9338db4e (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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtIvi module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/

#include "qdltregistration.h"
#include "qdltregistration_p.h"

#include <QDebug>
#include <QLoggingCategory>

#define GENIVIEXTRAS_DEBUG 0
#if GENIVIEXTRAS_DEBUG
#  include <iostream>
#endif

QT_BEGIN_NAMESPACE

void qtGeniviLogLevelChangedHandler(char context_id[], uint8_t log_level, uint8_t trace_status)
{
    auto d = globalDltRegistration()->d_ptr;
    d->m_mutex.lock();
    const QLoggingCategory *category = d->dltLogLevelChanged(context_id, log_level, trace_status);
    d->m_mutex.unlock();

    if (category)
        emit globalDltRegistration()->logLevelChanged(category);
}

Q_GLOBAL_STATIC(QDltRegistration, dltRegistration)

QDltRegistration *globalDltRegistration()
{
    return dltRegistration();
}

QT_END_NAMESPACE

QDltRegistrationPrivate::QDltRegistrationPrivate(QDltRegistration *parent)
    : q_ptr(parent)
    , m_dltAppRegistered(false)
    , m_registerOnFirstUse(false)
{
}

void QDltRegistrationPrivate::registerCategory(const QLoggingCategory *category, DltContext *dltContext, const char *dltCtxName, const char *dltCtxDescription)
{
    CategoryInfo info;
    info.m_category = const_cast<QLoggingCategory*>(category);
    info.m_ctxName = dltCtxName;
    info.m_ctxDescription = dltCtxDescription;
    info.m_context = dltContext;

    if (!m_registerOnFirstUse) {
        registerCategory(info);
    } else {
        info.m_registered = false;
    }

    m_categoryInfoHash.insert(QString::fromLatin1(category->categoryName()), info);
}

void QDltRegistrationPrivate::registerCategory(CategoryInfo &info)
{
#if GENIVIEXTRAS_DEBUG
    std::cout << "REGISTERING CONTEXT " << info.m_ctxName.constData() << std::endl;
#endif
    DLT_REGISTER_CONTEXT_LL_TS(*info.m_context, info.m_ctxName, info.m_ctxDescription, category2dltLevel(info.m_category), DLT_TRACE_STATUS_DEFAULT);

#if QT_CONFIG(dlt_2_12)
    //TODO move to lamda once c++11 is ok to be used
    DLT_REGISTER_LOG_LEVEL_CHANGED_CALLBACK(*info.m_context, &qtGeniviLogLevelChangedHandler);
#endif
    info.m_registered = true;
}

void QDltRegistrationPrivate::registerApplication()
{
    Q_ASSERT_X(!m_dltAppID.isEmpty(), "registerApplication", "dltAppID needs to be a valid char * on the first call.");
    DLT_REGISTER_APP(m_dltAppID.toLocal8Bit(), m_dltAppDescription.toLocal8Bit());
    m_dltAppRegistered = true;
}

void QDltRegistrationPrivate::unregisterApplication()
{
    if (m_dltAppRegistered)
        DLT_UNREGISTER_APP();

    m_dltAppRegistered = false;
}

void QDltRegistrationPrivate::setDefaultCategory(const QString &category)
{
    Q_ASSERT_X(m_categoryInfoHash.contains(category), "setDefaultContext", "The category needs to be registered as a dlt logging category before it can be set as a default context");
    m_defaultCategory = category;
}

DltContext *QDltRegistrationPrivate::context(const char *categoryName)
{
    QString category = QString::fromLatin1(categoryName);
    if (!m_categoryInfoHash.contains(category) && !m_defaultCategory.isEmpty())
        category = m_defaultCategory;

    CategoryInfo &info = m_categoryInfoHash[category];
    if (info.m_context && !info.m_registered) {
        if (!m_dltAppRegistered)
            registerApplication();
        registerCategory(info);
    }

    return info.m_context;
}

const QLoggingCategory * QDltRegistrationPrivate::dltLogLevelChanged(char context_id[], uint8_t log_level, uint8_t trace_status)
{
    Q_UNUSED(trace_status)

    const QLoggingCategory *changedCategory = nullptr;

    for (auto it = m_categoryInfoHash.begin(); it != m_categoryInfoHash.end(); ++it) {
        if (it.value().m_ctxName != context_id)
            continue;

        QList<QtMsgType> msgTypes;

        //Enable all QtLoggingCategories with a lower severity than the DLT level
        switch (log_level) {
        case DLT_LOG_VERBOSE:
        case DLT_LOG_DEBUG: msgTypes << QtDebugMsg << QtWarningMsg << QtCriticalMsg << QtFatalMsg;
#if QT_VERSION >= 0x050500
            msgTypes << QtInfoMsg;
#endif
            break;
        case DLT_LOG_INFO: msgTypes << QtWarningMsg << QtCriticalMsg << QtFatalMsg;
#if QT_VERSION >= 0x050500
            msgTypes << QtInfoMsg;
#endif
            break;
        case DLT_LOG_WARN: msgTypes << QtCriticalMsg << QtFatalMsg;
#if QT_VERSION >= 0x050500
            msgTypes << QtInfoMsg;
#endif
            break;
        case DLT_LOG_ERROR: msgTypes << QtCriticalMsg << QtFatalMsg;  break;
        case DLT_LOG_FATAL: msgTypes << QtFatalMsg; break;
        case DLT_LOG_OFF: msgTypes = QList<QtMsgType>(); break;
        }

        QtMsgType end = QtFatalMsg;
#if QT_VERSION >= 0x050500
        end = QtInfoMsg;
#endif

        for (auto i = int(QtDebugMsg); i <= int(end); i++) {
            auto type = QtMsgType(i);
            bool enabled = true;
            if (!msgTypes.contains(type))
                enabled = !enabled;
            QLoggingCategory* category = it.value().m_category;
            if (category->isEnabled(type) != enabled) {
                category->setEnabled(type, enabled);
                changedCategory = category;
            }
        }
        break;
    }

    return changedCategory;
}

DltLogLevelType QDltRegistrationPrivate::category2dltLevel(const QLoggingCategory *category)
{
    DltLogLevelType logLevel = DLT_LOG_OFF;

    if (category->isDebugEnabled())
        logLevel = DLT_LOG_DEBUG;
#if QT_VERSION >= 0x050500
    else if (category->isInfoEnabled())
        logLevel = DLT_LOG_INFO;
#endif
    else if (category->isWarningEnabled())
        logLevel = DLT_LOG_WARN;
    else if (category->isCriticalEnabled())
        logLevel = DLT_LOG_ERROR;

    return logLevel;
}

DltLogLevelType QDltRegistrationPrivate::severity2dltLevel(QtMsgType type)
{
    switch (type) {
    case QtDebugMsg: return DLT_LOG_DEBUG;
#if QT_VERSION >= 0x050500
    case QtInfoMsg: return DLT_LOG_INFO;
#endif
    case QtWarningMsg: return DLT_LOG_WARN;
    case QtCriticalMsg: return DLT_LOG_ERROR;
    case QtFatalMsg: return DLT_LOG_FATAL;
    }
    return DLT_LOG_OFF;
}

/*!
    \class QDltRegistration
    \inmodule QtGeniviExtras
    \brief The QDltRegistration class controls controls the mapping between QLoggingCategory and dlt context.

    The class talks to the dlt-daemon and provides a Qt messageHandler which forwards logging messages logged
    by the Qt Logging Framework to the dlt-daemon.

    Using dlt-daemon version 2.12 or higher it also reacts to DLT control messages and adapts the enabled msg
    types of a QLoggingCategory whenever the log level of a dlt context changes.
*/

QDltRegistration::QDltRegistration(QObject *parent)
    : QObject(parent)
    , d_ptr(new QDltRegistrationPrivate(this))
{
}

QDltRegistration::~QDltRegistration()
{
    unregisterApplication();
}

/*!
    Registers this application with the dlt-daemon using \a dltAppID and \a dltAppDescription.

    Per process only one application can be registered. Calling this function after an
    application is already registered, will register the application under the new \a dltAppID
    and \a dltAppDescription and also populating the already registered dlt contexts under this
    application. Calling the method with an empty \a dltAppID will update just the description
    if the app was already registered before.

    \sa QDLT_REGISTER_APPLICATION
*/
void QDltRegistration::registerApplication(const char *dltAppID, const char *dltAppDescription)
{
    Q_D(QDltRegistration);
    bool registerCategories = false;
    QMutexLocker l(&d->m_mutex);

    if (d->m_dltAppRegistered) {
        d->unregisterApplication();
        registerCategories = true;
    }

    if (dltAppID)
        d->m_dltAppID = QString::fromLatin1(dltAppID);
    d->m_dltAppDescription = QString::fromLatin1(dltAppDescription);

    if (!d->m_registerOnFirstUse)
        d->registerApplication();

    //Register all Contexts which already have been registered again under the new application
    if (registerCategories && !d->m_registerOnFirstUse) {
        for (auto it = d->m_categoryInfoHash.begin(); it != d->m_categoryInfoHash.end(); ++it) {
            if (it.value().m_registered)
                d->registerCategory(it.value());
        }
    }
}

/*!
    Registers \a category with the dlt-daemon using \a dltCtxName and \a dltCtxDescription.

    This function shouldn't be used directly, instead use the convenience macro.
    \sa QDLT_LOGGING_CATEGORY QDLT_REGISTER_LOGGING_CATEGORY
*/
void QDltRegistration::registerCategory(const QLoggingCategory *category, const char *dltCtxName, const char *dltCtxDescription)
{
    Q_D(QDltRegistration);
    Q_ASSERT(category);
    Q_ASSERT(strlen(category->categoryName()) != 0);
    QMutexLocker l(&d->m_mutex);
    d->registerCategory(category, new DltContext, dltCtxName, dltCtxDescription);
}

/*!
    Sets \a categoryName as the fallback logging category.

    \a categoryName needs to be the name of a valid QLoggingCategory which has been registered within the dlt-daemon.
    Either by using QDLT_LOGGING_CATEGORY or QDLT_REGISTER_LOGGING_CATEGORY.

    This function shouldn't be used directly, instead use the convenience macro.
    \sa QDLT_FALLBACK_CATEGORY
*/
void QDltRegistration::setDefaultContext(const char *categoryName)
{
    Q_D(QDltRegistration);
    QMutexLocker l(&d->m_mutex);
    d->setDefaultCategory(QString::fromLatin1(categoryName));
}

/*!
    When set to \a enabled the registration with the dlt-daemon is done on the first use of the category.

    Otherwise the registration is done directly when QDLT_LOGGING_CATEGORY or QDLT_REGISTER_LOGGING_CATEGORY
    is called.

    This function shouldn't be used directly, instead use the convenience macro.
    \sa QDLT_REGISTER_CONTEXT_ON_FIRST_USE
*/
void QDltRegistration::setRegisterContextOnFirstUseEnabled(bool enabled)
{
    Q_D(QDltRegistration);
    QMutexLocker l(&d->m_mutex);
    d->m_registerOnFirstUse = enabled;
}

/*!
    Registers all contexts with the dlt-daemon which are not yet registered.

    This function can be used in combination with setRegisterContextOnFirstUseEnabled to delay
    the registration with the dlt-daemon until it is really needed and once it is safe to register
    all context which haven't been registered yet, e.g. by using the associated logging category.

    \sa setRegisterContextOnFirstUseEnabled
*/
void QDltRegistration::registerUnregisteredContexts()
{
#if GENIVIEXTRAS_DEBUG
    std::cout << "REGISTERING UNREGISTERED CONTEXTS" << std::endl;
#endif
    Q_D(QDltRegistration);
    QMutexLocker l(&d->m_mutex);
    if (!d->m_dltAppRegistered)
        d->registerApplication();
    for (auto it = d->m_categoryInfoHash.begin(); it != d->m_categoryInfoHash.end(); ++it) {
        if (!it.value().m_registered) {
            d->registerCategory(it.value());
      }
    }
}

/*!
    Unregisters the application with the dlt-daemon.
    The registered application as well as all registered dlt context will be deleted.
*/
void QDltRegistration::unregisterApplication()
{
    Q_D(QDltRegistration);
    QMutexLocker l(&d->m_mutex);
    d->unregisterApplication();
}

/*!
    The Qt message handler which forwards all the logging messages to the dlt-daemon.

    The function will map \a msgTypes to the appropriate dlt log level and forward the \a msg to
    the dlt context matching the category in \a msgCtx.

    If the category in \a msgCtx hasn't been registered with a dlt context, the fallback logging category
    will be used instead (if one is registered).

    This messageHandler needs to be installed using:
    \badcode
    qInstallMessageHandler(QDltRegistration::messageHandler);
    \endcode
*/
void QDltRegistration::messageHandler(QtMsgType msgType, const QMessageLogContext &msgCtx, const QString &msg)
{
    if (!globalDltRegistration())
        return;

    QMutexLocker l(&globalDltRegistration()->d_ptr->m_mutex);

    DltContext *dltCtx = globalDltRegistration()->d_ptr->context(msgCtx.category);
    if (!dltCtx)
        return;

    DltLogLevelType logLevel = globalDltRegistration()->d_ptr->severity2dltLevel(msgType);

    DLT_LOG(*dltCtx, logLevel, DLT_STRING(qPrintable(qFormatLogMessage(msgType, msgCtx, msg))));
}

/*!
    \fn void QDltRegistration::logLevelChanged(const QLoggingCategory *category)

    This signal is emitted whenever the dlt-daemon changes the log level of a dlt context and
    the dlt context is registered with a QLoggingCategory. The updated QLoggingCategory is passed
    as \a category.

    \note This signal requires a dlt-daemon version equal to 2.12 or higher.
*/