Source

pyGAP / game / src / common / log.cpp

Full commit
#if defined(DEBUG)


#include "common/log.h"


#include <stdarg.h>
#include <cstring>
#include <cstdio>


namespace common {


#define LOG_BUFFER_SIZE     256


Log::log_map_t    Log::allocated_;


Log::Log(const char* context) :
    context_length_(0)
{
    buffer_ = new char [LOG_BUFFER_SIZE];

    context_length_ = strlen(context);
    if (context_length_ > LOG_BUFFER_SIZE)
        context_length_ = LOG_BUFFER_SIZE / 2;

    char fmt[10];
    sprintf(buffer_, "[%s] ", context);
    context_length_ = strlen(buffer_);
}


Log::~Log() {
    delete buffer_;
}


Log* Log::get(const char* context) {
    log_map_t::iterator it = allocated_.find(context);
    if (it != allocated_.end())
        return it->second;

    Log* log = new Log(context);
    allocated_[context] = log;
    return log;
}


void Log::clear() {
    for (log_map_t::iterator it = allocated_.begin(); it != allocated_.end(); ++it)
        delete it->second;
    allocated_.clear();
}


void Log::write(const char* format, ...) {
    va_list arg_list;
    va_start(arg_list, format);
    vsnprintf(buffer_ + context_length_,
              LOG_BUFFER_SIZE - context_length_,
              format, arg_list);
    va_end(arg_list);
    printf("%s", buffer_);
    fflush(stdout);
}


} /* namespace common */


#endif // defined(DEBUG)