logger.cpp 7.9 KB
Newer Older
1 2 3 4
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

5
#include "precomp.hpp"
6 7 8

#include <opencv2/core/utils/configuration.private.hpp>
#include <opencv2/core/utils/logger.hpp>
9 10
#include "utils/logtagmanager.hpp"
#include "utils/logtagconfigparser.hpp"
11 12 13 14 15

#include <sstream>
#include <iostream>
#include <fstream>

16 17 18 19
#ifdef __ANDROID__
# include <android/log.h>
#endif

20 21 22 23
namespace cv {
namespace utils {
namespace logging {

24
namespace internal
25
{
26 27 28 29 30 31 32

// Combining several things that require static dynamic initialization in a
// well-defined order into a struct.
//
struct GlobalLoggingInitStruct
{
public:
33
#if defined NDEBUG
34
    static const bool m_isDebugBuild = false;
35
#else
36
    static const bool m_isDebugBuild = true;
37
#endif
38 39

public:
40
    static LogLevel m_defaultUnconfiguredGlobalLevel;
41 42 43 44 45 46 47

public:
    LogTagManager logTagManager;

    GlobalLoggingInitStruct()
        : logTagManager(m_defaultUnconfiguredGlobalLevel)
    {
48 49
        (void)getInitializationMutex();  // ensure initialization of global objects

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
        applyConfigString();
        handleMalformed();
    }

private:
    void applyConfigString()
    {
        logTagManager.setConfigString(utils::getConfigurationParameterString("OPENCV_LOG_LEVEL", ""));
    }

    void handleMalformed()
    {
        // need to print warning for malformed log tag config strings?
        if (m_isDebugBuild)
        {
            const auto& parser = logTagManager.getConfigParser();
            if (parser.hasMalformed())
            {
                const auto& malformedList = parser.getMalformed();
                for (const auto& malformed : malformedList)
                {
                    std::cout << "Malformed log level config: \"" << malformed << "\"\n";
                }
                std::cout.flush();
            }
        }
    }
};

79
LogLevel GlobalLoggingInitStruct::m_defaultUnconfiguredGlobalLevel = GlobalLoggingInitStruct::m_isDebugBuild
80
                ? LOG_LEVEL_INFO
81 82 83
                : LOG_LEVEL_WARNING;


84 85 86 87 88 89 90 91 92 93 94 95 96
// Static dynamic initialization guard function for the combined struct
// just defined above
//
// An initialization guard function guarantees that outside code cannot
// accidentally see not-yet-dynamically-initialized data, by routing
// all outside access request to this function, so that this function
// has a chance to run the initialization code if necessary.
//
// An initialization guard function only guarantees initialization upon
// the first call to this function.
//
static GlobalLoggingInitStruct& getGlobalLoggingInitStruct()
{
97
    CV_SINGLETON_LAZY_INIT_REF(GlobalLoggingInitStruct, new GlobalLoggingInitStruct());
98 99 100 101 102 103 104 105 106 107 108 109
}

// To ensure that the combined struct defined above is initialized even
// if the initialization guard function wasn't called, a dummy static
// instance of a struct is defined below, which will call the
// initialization guard function.
//
struct GlobalLoggingInitCall
{
    GlobalLoggingInitCall()
    {
        getGlobalLoggingInitStruct();
110
        (void)getGlobalLogTag();  // complete initialization of logger structures
111 112 113 114 115 116 117 118 119
    }
};

static GlobalLoggingInitCall globalLoggingInitCall;

static LogTagManager& getLogTagManager()
{
    static LogTagManager& logTagManagerInstance = getGlobalLoggingInitStruct().logTagManager;
    return logTagManagerInstance;
120 121 122 123
}

static LogLevel& getLogLevelVariable()
{
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
    static LogLevel& refGlobalLogLevel = getGlobalLogTag()->level;
    return refGlobalLogLevel;
}

LogTag* getGlobalLogTag()
{
    static LogTag* globalLogTagPtr = getGlobalLoggingInitStruct().logTagManager.get("global");
    return globalLogTagPtr;
}

} // namespace

void registerLogTag(LogTag* plogtag)
{
    if (!plogtag || !plogtag->name)
    {
        return;
    }
    internal::getLogTagManager().assign(plogtag->name, plogtag);
}

void setLogTagLevel(const char* tag, LogLevel level)
{
    if (!tag)
    {
        return;
    }
    internal::getLogTagManager().setLevelByFullName(std::string(tag), level);
}

LogLevel getLogTagLevel(const char* tag)
{
    if (!tag)
    {
        return getLogLevel();
    }
    const LogTag* ptr = internal::getLogTagManager().get(std::string(tag));
    if (!ptr)
    {
        return getLogLevel();
    }
    return ptr->level;
166 167 168 169
}

LogLevel setLogLevel(LogLevel logLevel)
{
170 171 172 173
    // note: not thread safe, use sparingly and do not critically depend on outcome
    LogLevel& refGlobalLevel = internal::getLogLevelVariable();
    const LogLevel old = refGlobalLevel;
    refGlobalLevel = logLevel;
174 175 176 177 178
    return old;
}

LogLevel getLogLevel()
{
179
    return internal::getLogLevelVariable();
180 181 182 183
}

namespace internal {

184 185 186 187 188 189 190
static int getShowTimestampMode()
{
    static bool param_timestamp_enable = utils::getConfigurationParameterBool("OPENCV_LOG_TIMESTAMP", true);
    static bool param_timestamp_ns_enable = utils::getConfigurationParameterBool("OPENCV_LOG_TIMESTAMP_NS", false);
    return (param_timestamp_enable ? 1 : 0) + (param_timestamp_ns_enable ? 2 : 0);
}

191 192 193
void writeLogMessage(LogLevel logLevel, const char* message)
{
    const int threadID = cv::utils::getThreadID();
194 195 196 197 198

    std::string message_id;
    switch (getShowTimestampMode())
    {
        case 1: message_id = cv::format("%d@%0.3f", threadID, getTimestampNS() * 1e-9); break;
199
        case 1+2: message_id = cv::format("%d@%llu", threadID, (long long unsigned int)getTimestampNS()); break;
200 201 202
        default: message_id = cv::format("%d", threadID); break;
    }

203
    std::ostringstream ss;
204 205
    switch (logLevel)
    {
206 207 208 209 210
    case LOG_LEVEL_FATAL:   ss << "[FATAL:" << message_id << "] " << message << std::endl; break;
    case LOG_LEVEL_ERROR:   ss << "[ERROR:" << message_id << "] " << message << std::endl; break;
    case LOG_LEVEL_WARNING: ss << "[ WARN:" << message_id << "] " << message << std::endl; break;
    case LOG_LEVEL_INFO:    ss << "[ INFO:" << message_id << "] " << message << std::endl; break;
    case LOG_LEVEL_DEBUG:   ss << "[DEBUG:" << message_id << "] " << message << std::endl; break;
211
    case LOG_LEVEL_VERBOSE: ss << message << std::endl; break;
212 213
    case LOG_LEVEL_SILENT: return;  // avoid compiler warning about incomplete switch
    case ENUM_LOG_LEVEL_FORCE_INT: return;  // avoid compiler warning about incomplete switch
214
    }
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
#ifdef __ANDROID__
    int android_logLevel = ANDROID_LOG_INFO;
    switch (logLevel)
    {
    case LOG_LEVEL_FATAL:   android_logLevel = ANDROID_LOG_FATAL; break;
    case LOG_LEVEL_ERROR:   android_logLevel = ANDROID_LOG_ERROR; break;
    case LOG_LEVEL_WARNING: android_logLevel = ANDROID_LOG_WARN; break;
    case LOG_LEVEL_INFO:    android_logLevel = ANDROID_LOG_INFO; break;
    case LOG_LEVEL_DEBUG:   android_logLevel = ANDROID_LOG_DEBUG; break;
    case LOG_LEVEL_VERBOSE: android_logLevel = ANDROID_LOG_VERBOSE; break;
    default:
        break;
    }
    __android_log_print(android_logLevel, "OpenCV/" CV_VERSION, "%s", ss.str().c_str());
#endif
    std::ostream* out = (logLevel <= LOG_LEVEL_WARNING) ? &std::cerr : &std::cout;
231 232 233 234 235
    (*out) << ss.str();
    if (logLevel <= LOG_LEVEL_WARNING)
        (*out) << std::flush;
}

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
static const char* stripSourceFilePathPrefix(const char* file)
{
    CV_Assert(file);
    const char* pos = file;
    const char* strip_pos = NULL;
    char ch = 0;
    while ((ch = pos[0]) != 0)
    {
        ++pos;
        if (ch == '/' || ch == '\\')
            strip_pos = pos;
    }
    if (strip_pos == NULL || strip_pos == pos/*eos*/)
        return file;
    return strip_pos;
}

253 254 255 256 257
void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message)
{
    std::ostringstream strm;
    if (tag)
    {
258
        strm << tag << ' ';
259 260 261
    }
    if (file)
    {
262 263 264 265 266 267
        strm << stripSourceFilePathPrefix(file);
        if (line > 0)
        {
            strm << ':' << line;
        }
        strm << ' ';
268 269 270
    }
    if (func)
    {
271
        strm << func << ' ';
272 273 274 275 276
    }
    strm << message;
    writeLogMessage(logLevel, strm.str().c_str());
}

277 278 279
} // namespace

}}} // namespace