Skip to content

Commit

Permalink
Make logger thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
m-seker committed Jul 18, 2020
1 parent ebba77f commit 848e290
Show file tree
Hide file tree
Showing 9 changed files with 250 additions and 168 deletions.
1 change: 0 additions & 1 deletion assets/webconfig/js/content_logging.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
requestLoggingStart();

$(document).ready(function() {

var messages;
var loguplmess = "";
var reportUrl = 'https://report.hyperion-project.org/#';
Expand Down
85 changes: 47 additions & 38 deletions include/utils/Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,33 @@
// QT includes
#include <QObject>
#include <QString>
#include <QMap>
#include <QAtomicInteger>
#include <QList>
#include <QMutex>

// stl includes
#include <stdio.h>
#include <stdarg.h>
#include <map>
#include <QVector>
#ifdef _WIN32
#include <stdexcept>
#endif

#include <utils/global_defines.h>

#define LOG_MESSAGE(severity, logger, ...) (logger)->Message(severity, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)

// standard log messages
#define Debug(logger, ...) (logger)->Message(Logger::DEBUG , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define Info(logger, ...) (logger)->Message(Logger::INFO , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define Warning(logger, ...) (logger)->Message(Logger::WARNING, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define Error(logger, ...) (logger)->Message(Logger::ERRORR , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define Debug(logger, ...) LOG_MESSAGE(Logger::DEBUG , logger, __VA_ARGS__)
#define Info(logger, ...) LOG_MESSAGE(Logger::INFO , logger, __VA_ARGS__)
#define Warning(logger, ...) LOG_MESSAGE(Logger::WARNING, logger, __VA_ARGS__)
#define Error(logger, ...) LOG_MESSAGE(Logger::ERROR , logger, __VA_ARGS__)

// conditional log messages
#define DebugIf(condition, logger, ...) if (condition) (logger)->Message(Logger::DEBUG , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define InfoIf(condition, logger, ...) if (condition) (logger)->Message(Logger::INFO , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define WarningIf(condition, logger, ...) if (condition) (logger)->Message(Logger::WARNING , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define ErrorIf(condition, logger, ...) if (condition) (logger)->Message(Logger::ERRORR , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define DebugIf(condition, logger, ...) if (condition) Debug(logger, __VA_ARGS__)
#define InfoIf(condition, logger, ...) if (condition) Info(logger, __VA_ARGS__)
#define WarningIf(condition, logger, ...) if (condition) Warning(logger, __VA_ARGS__)
#define ErrorIf(condition, logger, ...) if (condition) Error(logger, __VA_ARGS__)

// ================================================================

Expand All @@ -35,62 +39,68 @@ class Logger : public QObject

public:
enum LogLevel {
UNSET,
DEBUG,
INFO,
WARNING,
ERRORR,
OFF
UNSET = 0,
DEBUG = 1,
INFO = 2,
WARNING = 3,
ERROR = 4,
OFF = 5
};

typedef struct
struct T_LOG_MESSAGE
{
QString appName;
QString loggerName;
QString function;
unsigned int line;
QString fileName;
time_t utime;
uint64_t utime;
QString message;
LogLevel level;
QString levelString;
} T_LOG_MESSAGE;
};

static Logger* getInstance(QString name="", LogLevel minLevel=Logger::INFO);
static void deleteInstance(QString name="");
static void setLogLevel(LogLevel level, QString name="");
static LogLevel getLogLevel(QString name="");
static Logger* getInstance(const QString & name = "", LogLevel minLevel=Logger::INFO);
static void deleteInstance(const QString & name = "");
static void setLogLevel(LogLevel level, const QString & name = "");
static LogLevel getLogLevel(const QString & name = "");

void Message(LogLevel level, const char* sourceFile, const char* func, unsigned int line, const char* fmt, ...);
void setMinLevel(LogLevel level) { _minLevel = level; }
LogLevel getMinLevel() { return _minLevel; }
void setMinLevel(LogLevel level) { _minLevel = static_cast<int>(level); }
LogLevel getMinLevel() { return static_cast<LogLevel>(int(_minLevel)); }
QString getName() const { return _name; }
QString getAppName() const { return _appname; }

signals:
void newLogMessage(Logger::T_LOG_MESSAGE);

protected:
Logger( QString name="", LogLevel minLevel=INFO);
Logger(const QString & name="", LogLevel minLevel = INFO);
~Logger();

private:
static std::map<QString,Logger*> *LoggerMap;
static LogLevel GLOBAL_MIN_LOG_LEVEL;

QString _name;
QString _appname;
LogLevel _minLevel;
bool _syslogEnabled;
unsigned _loggerId;
};
void write(const Logger::T_LOG_MESSAGE & message) const;

static QMutex MapLock;
static QMap<QString,Logger*> LoggerMap;
static QAtomicInteger<int> GLOBAL_MIN_LOG_LEVEL;

const QString _name;
const QString _appname;
const bool _syslogEnabled;
const unsigned _loggerId;

/* Only non-const member, hence the atomic */
QAtomicInteger<int> _minLevel;
};

class LoggerManager : public QObject
{
Q_OBJECT

public:
static LoggerManager* getInstance();
QVector<Logger::T_LOG_MESSAGE>* getLogMessageBuffer() { return &_logMessageBuffer; }
const QList<Logger::T_LOG_MESSAGE>* getLogMessageBuffer() const { return &_logMessageBuffer; }

public slots:
void handleNewLogMessage(const Logger::T_LOG_MESSAGE&);
Expand All @@ -101,8 +111,7 @@ public slots:
protected:
LoggerManager();

static LoggerManager* _instance;
QVector<Logger::T_LOG_MESSAGE> _logMessageBuffer;
QList<Logger::T_LOG_MESSAGE> _logMessageBuffer;
const int _loggerMaxMsgBufferSize;
};

Expand Down
2 changes: 1 addition & 1 deletion libsrc/api/JsonAPI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1548,7 +1548,7 @@ void JsonAPI::incommingLogMessage(const Logger::T_LOG_MESSAGE &msg)
if (!_streaming_logging_activated)
{
_streaming_logging_activated = true;
QVector<Logger::T_LOG_MESSAGE> *logBuffer = LoggerManager::getInstance()->getLogMessageBuffer();
const QList<Logger::T_LOG_MESSAGE> *logBuffer = LoggerManager::getInstance()->getLogMessageBuffer();
for (int i = 0; i < logBuffer->length(); i++)
{
message["appName"] = logBuffer->at(i).appName;
Expand Down
2 changes: 1 addition & 1 deletion libsrc/flatbufserver/FlatBufferConnection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ FlatBufferConnection::FlatBufferConnection(const QString& origin, const QString
, _origin(origin)
, _priority(priority)
, _prevSocketState(QAbstractSocket::UnconnectedState)
, _log(Logger::getInstance("FLATBUFCONNECTION"))
, _log(Logger::getInstance("FLATBUFCONN"))
, _registered(false)
{
QStringList parts = address.split(":");
Expand Down
2 changes: 1 addition & 1 deletion libsrc/hyperion/ComponentRegister.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ using namespace hyperion;

ComponentRegister::ComponentRegister(Hyperion* hyperion)
: _hyperion(hyperion)
, _log(Logger::getInstance("ComponentRegister"))
, _log(Logger::getInstance("COMPONENTREG"))
{
// init all comps to false
QVector<hyperion::Components> vect;
Expand Down
2 changes: 1 addition & 1 deletion libsrc/hyperion/Grabber.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Grabber::Grabber(QString grabberName, int width, int height, int cropLeft, int c
, _cropTop(0)
, _cropBottom(0)
, _enabled(true)
, _log(Logger::getInstance(grabberName))
, _log(Logger::getInstance(grabberName.toUpper()))
{
Grabber::setVideoMode(VideoMode::VIDEO_2D);
Grabber::setCropping(cropLeft, cropRight, cropTop, cropBottom);
Expand Down
2 changes: 1 addition & 1 deletion libsrc/hyperion/SettingsManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ QJsonObject SettingsManager::schemaJson;

SettingsManager::SettingsManager(const quint8& instance, QObject* parent)
: QObject(parent)
, _log(Logger::getInstance("SettingsManager"))
, _log(Logger::getInstance("SETTINGSMGR"))
, _sTable(new SettingsTable(instance, this))
{
// get schema
Expand Down
89 changes: 70 additions & 19 deletions libsrc/utils/DefaultSignalHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,35 @@

namespace DefaultSignalHandler
{
struct Signal
{
int number;
const char * name;
};

const Signal ALL_SIGNALS[] = {
{ SIGABRT, "SIGABRT" },
{ SIGBUS, "SIGBUS" },
{ SIGFPE, "SIGFPE" },
{ SIGILL, "SIGILL" },
{ SIGSEGV, "SIGSEGV" },
{ SIGTERM, "SIGTERM" },
{ SIGHUP, "SIGHUP" },
{ SIGINT, "SIGINT" },
{ SIGPIPE, "SIGPIPE" },
};

void write_to_stderr(const char* data, size_t size)
{
int res = write(STDERR_FILENO, data, size);

Q_UNUSED(res);
}

void write_to_stderr(const char* data)
{
write_to_stderr(data, strlen(data));
}

std::string decipher_trace(const std::string &trace)
{
Expand Down Expand Up @@ -70,26 +99,48 @@ void print_trace()
free(symbols);
}

void install_default_handler(int signum)
{
struct sigaction action{};
sigemptyset(&action.sa_mask);
action.sa_handler = SIG_DFL;
(void)sigaction(signum, &action, nullptr);
}

/* Note that this signal handler is not async signal safe !
* Ideally a signal handler should only flip a bit and defer
* heavy work to some kind of bottom-half processing. */
void signal_handler(int signum, siginfo_t * /*info*/, void * /*context*/)
{
Logger* log = Logger::getInstance("SIGNAL");
const char * name = "UNKNOWN SIGNAL";

char *name = strsignal(signum);
if (name)
{
Info(log, "Signal received : %s", name);
for (const auto& s : ALL_SIGNALS) {
if (s.number == signum) {
name = s.name;
break;
}
}

write_to_stderr("\n");
write_to_stderr("Hyperion caught signal :");
write_to_stderr(name);
write_to_stderr("\n");

/* Anything below here is unsafe ! */

switch(signum)
{
case SIGBUS:
case SIGSEGV:
case SIGABRT:
case SIGFPE :
print_trace();
exit(1);

/* Don't catch our own signal */
install_default_handler(signum);

kill(getpid(), signum);
return;
case SIGINT :
case SIGTERM:
case SIGPIPE:
Expand All @@ -101,10 +152,7 @@ void signal_handler(int signum, siginfo_t * /*info*/, void * /*context*/)
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);

// Reset signal handler to default (in case this handler is not capable of stopping)
struct sigaction action{};
action.sa_handler = SIG_DFL;
sigaction(signum, &action, nullptr);

install_default_handler(signum);
}
}

Expand All @@ -116,17 +164,20 @@ namespace DefaultSignalHandler
void install()
{
#ifndef _WIN32
Logger* log = Logger::getInstance("CORE");

struct sigaction action{};
sigemptyset(&action.sa_mask);
action.sa_sigaction = signal_handler;
action.sa_flags = SA_RESTART | SA_SIGINFO;

sigaction(SIGHUP , &action, nullptr);
sigaction(SIGFPE , &action, nullptr);
sigaction(SIGINT , &action, nullptr);
sigaction(SIGTERM, &action, nullptr);
sigaction(SIGABRT, &action, nullptr);
sigaction(SIGSEGV, &action, nullptr);
sigaction(SIGPIPE, &action, nullptr);
action.sa_flags |= SA_SIGINFO;

for (const auto& s : ALL_SIGNALS)
{
if (sigaction(s.number, &action, nullptr)!= 0)
{
Error(log, "Failed to install handler for %s]\n", s.name);
}
}
#endif // _WIN32
}
} // namespace DefaultSignalHandler
Loading

0 comments on commit 848e290

Please sign in to comment.