common.cpp 9.3 KB
Newer Older
1 2 3 4
/**
 * \file src/core/impl/common.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#include "megbrain/common.h"
#include "megbrain/exception.h"
#include "megbrain/system.h"
#include "megbrain/utils/thread.h"

#include "megdnn/basic_types.h"

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>

#ifdef __ANDROID__
#include <android/log.h>
26
#include <sys/system_properties.h>
27 28 29 30 31
#endif

using namespace mgb;

namespace {
M
Megvii Engine Team 已提交
32 33 34 35
LogLevel config_default_log_level() {
    auto default_level = LogLevel::ERROR;
    //! env to config LogLevel
    //!  DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3, NO_LOG = 4
36
    //! for example , export RUNTIME_OVERRIDE_LOG_LEVEL=0, means set LogLevel to
M
Megvii Engine Team 已提交
37
    //! DEBUG
38
    if (auto env = ::std::getenv("RUNTIME_OVERRIDE_LOG_LEVEL"))
M
Megvii Engine Team 已提交
39 40
        default_level = static_cast<LogLevel>(std::stoi(env));

41 42 43 44 45 46 47 48
#ifdef __ANDROID__
    //! special for Android prop, attention: getprop may need permission
    char buf[PROP_VALUE_MAX];
    if (__system_property_get("RUNTIME_OVERRIDE_LOG_LEVEL", buf) > 0) {
        default_level = static_cast<LogLevel>(atoi(buf));
    }
#endif

M
Megvii Engine Team 已提交
49
    return default_level;
50 51
}

M
Megvii Engine Team 已提交
52 53 54
LogLevel min_log_level = config_default_log_level();
}  // namespace

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
#if MGB_ENABLE_LOGGING

#if MGB_EXTERN_API_TIME
extern "C" {
    void mgb_extern_api_get_time(int64_t *sec, int64_t *nsec);
}
#endif

namespace {
void default_log_handler(LogLevel level,
        const char *file, const char *func, int line, const char *fmt,
        va_list ap) {
    if (level < min_log_level)
        return;

#define HDR_FMT	"[%s %s@%s:%d]%s"
    fmt = convert_fmt_str(fmt);

    // we have to use a Spinlock here, since log handler might be called during
    // global finalization when mtx has been destructed
    static Spinlock mtx;

    static const char *hdr_fmt = nullptr;
    if (!hdr_fmt) {
        if (sys::stderr_ansi_color())
            hdr_fmt = "\x1b[32m" HDR_FMT "\x1b[0m ";
        else
            hdr_fmt = HDR_FMT " ";
    }
    const char *warn_reminder = "";
    switch (level) {
        case LogLevel::ERROR:
            if (sys::stderr_ansi_color())
                warn_reminder = "\x1b[1;4;31m[ERR]\x1b[0m";
            else
                warn_reminder = "[ERR]";
            break;
        case LogLevel::WARN:
            if (sys::stderr_ansi_color())
                warn_reminder = "\x1b[1;31m[WARN]\x1b[0m";
            else
                warn_reminder = "[WARN]";
            break;
        case LogLevel::INFO:
            break;
        case LogLevel::DEBUG:
            if (sys::stderr_ansi_color())
                warn_reminder = "\x1b[36m[DEBUG]\x1b[0m";
            else
                warn_reminder = "[DEBUG]";
            break;
        default:
            mgb_throw(MegBrainError, "bad log level");
    }
    char timestr[64];
#if MGB_EXTERN_API_TIME
    {
        static int64_t sec_start, nsec_start;
        int64_t sec, nsec;
        mgb_extern_api_get_time(&sec, &nsec);
        if (!sec_start) {
            sec_start = sec;
            nsec_start = nsec;
        }
        sec -= sec_start;
        nsec -= nsec_start;
        if (nsec < 0) {
            -- sec;
            nsec += 1000000000;
        }
        snprintf(timestr, sizeof(timestr), "%.3f",
                static_cast<int>(sec) + static_cast<int>(nsec) * 1e-9);
    }
#else
    {
        time_t cur_time;
        MGB_LOCK_GUARD(mtx);
        time(&cur_time);
        strftime(timestr, sizeof(timestr), "%d %H:%M:%S", localtime(&cur_time));
    }
#endif

    {
        // find file basename part
        auto f0 = file;
        file = f0 + strlen(f0) - 1;
        while (file >= f0 && *file != '/' && *file != '\\')
            -- file;
        ++ file;
    }
    {
        MGB_LOCK_GUARD(mtx);
        fprintf(stderr, hdr_fmt, timestr, func, file, line, warn_reminder);
        vfprintf(stderr, fmt, ap);
        fputc('\n', stderr);
    }

#ifdef __ANDROID__
    android_LogPriority android_level;
    switch (level) {
        case LogLevel::WARN:
            android_level = ANDROID_LOG_WARN;
            break;
        case LogLevel::INFO:
            android_level = ANDROID_LOG_INFO;
            break;
        case LogLevel::DEBUG:
            android_level = ANDROID_LOG_DEBUG;
            break;
        default:
            android_level = ANDROID_LOG_ERROR;
    }
167
    __android_log_vprint(android_level, "runtime", fmt, ap);
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
#endif

#undef HDR_FMT
}

LogHandler log_handler = default_log_handler;

class MegDNNLogHandler {
    static void dnn_log_handler(megdnn::LogLevel dnn_level, const char* file,
                                const char* func, int line, const char* fmt,
                                va_list ap) {
        mgb::LogLevel mgb_level;
        switch (dnn_level) {
            case megdnn::LogLevel::DEBUG:
                mgb_level = LogLevel::DEBUG;
                break;
            case megdnn::LogLevel::INFO:
                mgb_level = LogLevel::INFO;
                break;
            case megdnn::LogLevel::WARN:
                mgb_level = LogLevel::WARN;
                break;
            default:
                mgb_level = LogLevel::ERROR;
        }
        if (mgb_level < min_log_level) {
            return;
        }

197
        std::string new_fmt{"[dnn] "};
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
        new_fmt.append(fmt);
        log_handler(mgb_level, file, func, line, new_fmt.c_str(), ap);
    }

public:
    MegDNNLogHandler() { megdnn::set_log_handler(dnn_log_handler); }
};
MegDNNLogHandler g_megdnn_log_handler_init;
}  // anonymous namespace

void mgb::__log__(LogLevel level,
        const char *file, const char *func, int line, const char *fmt, ...) {
    if (level < min_log_level)
        return;

    va_list ap;
    va_start(ap, fmt);
    log_handler(level, file, func, line, fmt, ap);
    va_end(ap);
}

/* ===================== forward log in MegWave ===================== */
// common::Log is a weak symbol in megwave
namespace common {
enum class LogLevel { kInfo, kWarn, kDebug, kFatal };
void Log(LogLevel level, char const* file, int line, char const* func,
        char const *fmt, ...) {

    std::string new_fmt("[megwave] ");
    new_fmt.append(fmt);
    va_list ap;
    va_start(ap, fmt);
    log_handler(level == LogLevel::kWarn ? mgb::LogLevel::WARN :
            mgb::LogLevel::DEBUG,
            file, func, line, new_fmt.c_str(), ap);
    va_end(ap);
}
}

#else // MGB_ENABLE_LOGGING

namespace {
    void default_log_handler(LogLevel ,
        const char *, const char *, int , const char *,
        va_list ) {
    }
    LogHandler log_handler = default_log_handler;
}

#endif // MGB_ENABLE_LOGGING

LogLevel mgb::set_log_level(LogLevel level) {
250
    if (auto env = ::std::getenv("RUNTIME_OVERRIDE_LOG_LEVEL"))
M
Megvii Engine Team 已提交
251 252
        level = static_cast<LogLevel>(std::stoi(env));

253 254 255 256 257 258 259 260
#ifdef __ANDROID__
    //! special for Android prop, attention: getprop may need permission
    char buf[PROP_VALUE_MAX];
    if (__system_property_get("RUNTIME_OVERRIDE_LOG_LEVEL", buf) > 0) {
        level = static_cast<LogLevel>(atoi(buf));
    }
#endif

261 262 263 264 265
    auto ret = min_log_level;
    min_log_level = level;
    return ret;
}

M
Megvii Engine Team 已提交
266 267 268 269
LogLevel mgb::get_log_level() {
    return min_log_level;
}

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
LogHandler mgb::set_log_handler(LogHandler handler) {
    auto ret = log_handler;
    log_handler = handler;
    return ret;
}

void mgb::__assert_fail__(
        const char *file, int line, const char *func,
        const char *expr, const char *msg_fmt, ...) {

    std::string msg = ssprintf("assertion `%s' failed at %s:%d: %s",
            expr, file, line, func);
    if (msg_fmt) {
        msg_fmt = convert_fmt_str(msg_fmt);
        va_list ap;
        va_start(ap, msg_fmt);
        msg.append("\nextra message: ");
        msg.append(svsprintf(msg_fmt, ap));
        va_end(ap);
    }
    mgb_throw_raw(AssertionError{msg});
}

#if MGB_ENABLE_LOGGING && !MGB_ENABLE_EXCEPTION
void mgb::__on_exception_throw__(const std::exception &exc) {
    mgb_log_error("exception thrown: %s", exc.what());
    mgb_log_error("abort now due to previous error");
    mgb_trap();
}
#endif

std::string mgb::svsprintf(const char *fmt, va_list ap_orig) {
    fmt = convert_fmt_str(fmt);
    int size = 100;     /* Guess we need no more than 100 bytes */
    char *p;

    if ((p = (char*)malloc(size)) == nullptr)
        goto err;

    for (; ;) {
        va_list ap;
        va_copy(ap, ap_orig);
        int n = vsnprintf(p, size, fmt, ap);
        va_end(ap);

#ifdef WIN32
        if (n == -1) {
            n = _vscprintf(fmt, ap_orig);
            mgb_assert(n >= size);
        }
#endif

        if (n < 0)
            goto err;

        if (n < size) {
            std::string rst(p);
            free(p);
            return rst;
        }

        size = n + 1;

        char *np = (char*)realloc(p, size);
        if (!np) {
            free(p);
            goto err;
        } else
            p = np;
    }

err:
    fprintf(stderr, "could not allocate memory for svsprintf; fmt=%s\n",
            fmt);
    mgb_trap();
}

std::string mgb::ssprintf(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    auto rst = svsprintf(fmt, ap);
    va_end(ap);
    return rst;
}


// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}