jeremy-rifkin / libassert

The most over-engineered C++ assertion library
MIT License
539 stars 36 forks source link

Custom printer? #72

Closed nickdademo closed 11 months ago

nickdademo commented 11 months ago

First of all, very nice library! :)

I wonder if there is some way to hook into the generation of the assert string/message? Maybe via a custom printer class?

In our current Qt app, we have a hand-rolled ASSERT_FATAL() macro to catch things that shouldn't happen in release builds. After the Q_ASSERT_X debug-only assert, the Qt qFatal() call logs the message to a log file and then calls abort(). This is nice as we can just look at the log file after a customer reports a crash and can easily check if it was due to a violation of one of these assert macros. Code below:

#define ASSERT_FATAL(CONDITION, WHAT)                                   \
{                                                                       \
    genericAssertFatal((CONDITION) ? true : false, __FUNCTION__, WHAT); \
}

inline void genericAssertFatal(bool condition, const char *functionName, const QString &text)
{
    Q_ASSERT_X(condition, functionName, text.toStdString().c_str());
    if (!condition)
    {
        const auto messageStr = std::string(functionName) + ": " + text.toStdString();
        qFatal(messageStr.c_str());
    }
}

Would also be interesting to be able to dump the output to a file as well.

jeremy-rifkin commented 11 months ago

Hi @nickdademo, thanks for your interest in the library!

Does a custom failure handler work for your use case? Custom failure handlers can be specified with -DASSERT_FAIL=fn and then there's an example handler here https://github.com/jeremy-rifkin/libassert/tree/main#configuration. This should give you full control over how the message is printed / logged and what is done on a failure (e.g. whether it calls abort() or throws or whatnot).

jeremy-rifkin commented 11 months ago

I'm going to go ahead and close this issue for now, please let me know if anything about the custom handlers are lacking for your use case or if you have any other questions!