void Log::write (LogMessage log_message) { for (int i = 0; (unsigned) i < Log::loggers.size(); i++) { if (Log::loggers[i]->get_level() >= log_message.get_level() ) { Log::loggers[i]->write(log_message); } } }
// helper for fatal CHECK std::string fatalCheckToString(const LogMessage& msg) { auto out = LogDetailsToString(msg); static const std::string contractExitReason = {"EXIT trigger caused by broken Contract:"}; out.append("\n\t*******\t " + contractExitReason + " CHECK(" + msg.expression() + ")\n\t" + '"' + msg. message() + '"'); return out; }
void LogAppenderBase::log(const LogMessage& message) { if(message.getLogLevel() >= m_logLevel) { logMessage(message); } }
void Appender::write(LogMessage& message) { if (!level || level > message.level) return; message.prefix.clear(); if (flags & APPENDER_FLAGS_PREFIX_TIMESTAMP) message.prefix.append(message.getTimeStr()); if (flags & APPENDER_FLAGS_PREFIX_LOGLEVEL) { if (!message.prefix.empty()) message.prefix.push_back(' '); char text[MAX_QUERY_LEN]; snprintf(text, MAX_QUERY_LEN, "%-5s", Appender::getLogLevelString(message.level)); message.prefix.append(text); } if (flags & APPENDER_FLAGS_PREFIX_LOGFILTERTYPE) { if (!message.prefix.empty()) message.prefix.push_back(' '); message.prefix.push_back('['); message.prefix.append(message.type); message.prefix.push_back(']'); } if (!message.prefix.empty()) message.prefix.push_back(' '); _write(message); }
void StandardLogHandler::handleMessage( const LogMessage& message, const LogCategory* handlerCategory) { if (message.getLevel() < getLevel()) { return; } writer_->writeMessage(formatter_->formatMessage(message, handlerCategory)); }
// ajoute un message de log dans un fichier, et écriture dans la console void LogSystem::add(LogMessage log) { QTextStream cout(stdout, QIODevice::WriteOnly); QFile fichier("fichierDeLog.txt"); // ouverture en mode Append, pour écrire à la fin. fichier.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append); QTextStream flux(&fichier); QString tmp = log.toString().c_str(); // écriture du log dans le fichier flux << tmp << "\n"; // éciture du log sur la console cout << "Ecriture dans le fichier de log : " << log.toString().c_str() << endl; fichier.close(); }
std::string FileLogHandler::messagePrefix(const LogMessage & message) { std::string prefix = levelString(message.level()); if (!message.context().empty()) { if (!prefix.empty()) prefix = prefix + " "; prefix = prefix + "[" + message.context() + "]"; } if (prefix.empty()) return prefix; return prefix + ": "; }
TEST(LogMessagePoolTests, GetAndRelease) { static const size_t INITIAL_CAPACITY=128; static const size_t MAX_CAPACITY= 1024; static const size_t MAX_RETURNED_MESSAGE_SIZE= 256; static const size_t INITIAL_POOL_SIZE= 4; static const size_t MAX_POOL_SIZE= 8; TestingLogMessagePool factory(INITIAL_CAPACITY, MAX_CAPACITY, MAX_RETURNED_MESSAGE_SIZE, INITIAL_POOL_SIZE, MAX_POOL_SIZE); std::vector<LogMessage*> messagesInPool; std::vector<LogMessage*> newMessagesInPool; LogMessage* msg; messagesInPool.reserve(INITIAL_POOL_SIZE); factory.getMessagesInPool(std::back_inserter(messagesInPool)); EXPECT_EQ(messagesInPool.size(), INITIAL_POOL_SIZE); msg= factory.get(); EXPECT_EQ(msg->capacity(), factory.initialMessageSize()); EXPECT_EQ(msg->maxCapacity(), factory.maxMessageSize()); EXPECT_TRUE(msg->empty()); // Verify the message came from the pool EXPECT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE-1); EXPECT_TRUE(std::find(messagesInPool.begin(), messagesInPool.end(), msg) != messagesInPool.end()); // Verify the message returned to the pool factory.release(msg); EXPECT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE); factory.getMessagesInPool(std::back_inserter(newMessagesInPool)); std::sort(messagesInPool.begin(), messagesInPool.end()); std::sort(newMessagesInPool.begin(), newMessagesInPool.end()); if (messagesInPool != newMessagesInPool) { std::ostringstream details; details << "messagesInPool != newMessagesInPool\n messagesInPool = [ " << join(messagesInPool.begin(), messagesInPool.end(), ", ") << " ]\n newMessagesInPool = [ " << join(newMessagesInPool.begin(), newMessagesInPool.end(), ", ") << " ]"; EXPECT_TRUE(false) << details.str(); } }
void Console::log(const LogMessage& message) { if (message.string().empty()) return; logToDebug(message); logToFile(message); if (m_textCtrl != NULL) logToConsole(message); else m_buffer.push_back(message); }
// Format and print the message // ============================================================================================= void LoggerFactory::logToStdOut(const LogMessage& message) { std::stringstream ss(message.toString()); std::string line; while (std::getline(ss, line, '\n')) { line += "\n"; std::printf(line.c_str()); } }
void Console::logToConsole(const LogMessage& message) { long start = m_textCtrl->GetLastPosition(); m_textCtrl->AppendText(message.string()); m_textCtrl->AppendText("\n"); long end = m_textCtrl->GetLastPosition(); switch (message.level()) { case LLDebug: m_textCtrl->SetStyle(start, end, wxTextAttr(*wxLIGHT_GREY, *wxBLACK)); // SetDefaultStyle doesn't work on OS X / Cocoa break; case LLInfo: m_textCtrl->SetStyle(start, end, wxTextAttr(*wxWHITE, *wxBLACK)); // SetDefaultStyle doesn't work on OS X / Cocoa break; case LLWarn: m_textCtrl->SetStyle(start, end, wxTextAttr(*wxYELLOW, *wxBLACK)); // SetDefaultStyle doesn't work on OS X / Cocoa break; case LLError: m_textCtrl->SetStyle(start, end, wxTextAttr(*wxRED, *wxBLACK)); // SetDefaultStyle doesn't work on OS X / Cocoa break; } }
bool LogFilterRegex::DoesMatch(const LogMessage &message) const { switch (m_filter_target) { case eFilterTargetActivity: // Empty fields never match a condition. if (!message.HasActivity()) return false; return ::regexec(&m_regex, message.GetActivity(), 0, nullptr, 0) == 0; case eFilterTargetActivityChain: // Empty fields never match a condition. if (!message.HasActivity()) return false; return ::regexec(&m_regex, message.GetActivityChain().c_str(), 0, nullptr, 0) == 0; case eFilterTargetCategory: // Empty fields never match a condition. if (!message.HasCategory()) return false; return ::regexec(&m_regex, message.GetCategory(), 0, nullptr, 0) == 0; case eFilterTargetMessage: { const char *message_text = message.GetMessage(); if (!message_text) { DNBLogThreadedIf(LOG_DARWIN_LOG, "LogFilterRegex: regex " "\"%s\" no match due to nullptr message.", m_regex_text.c_str()); return false; } bool match = ::regexec(&m_regex, message_text, 0, nullptr, 0) == 0; DNBLogThreadedIf(LOG_DARWIN_LOG, "LogFilterRegex: regex " "\"%s\" %s message \"%s\".", m_regex_text.c_str(), match ? "matches" : "does not match", message_text); return match; } case eFilterTargetSubsystem: // Empty fields never match a condition. if (!message.HasSubsystem()) return false; return ::regexec(&m_regex, message.GetSubsystem(), 0, nullptr, 0) == 0; default: // We don't know this type. return false; } }
void LogManager::log(LogMessage msg) { //don't do any formatting changes or filtering to the TTY output since we //use the raw output to do diffs with the output of a real PS3 and some //programs write text in single bytes to the console if (msg.mType != TTY) { std::string prefix; switch (msg.mServerity) { case Success: prefix = "S "; break; case Notice: prefix = "! "; break; case Warning: prefix = "W "; break; case Error: prefix = "E "; break; } if (NamedThreadBase* thr = GetCurrentNamedThread()) { prefix += "{" + thr->GetThreadName() + "} "; } msg.mText.insert(0, prefix); msg.mText.append(1,'\n'); } #ifdef BUFFERED_LOGGING size_t size = msg.size(); std::vector<char> temp_buffer(size); msg.serialize(temp_buffer.data()); mBuffer.pushRange(temp_buffer.begin(), temp_buffer.end()); mBufferReady.notify_one(); #else mChannels[static_cast<u32>(msg.mType)].log(msg); #endif }
TEST(LogMessagePoolTests, ReturnTooLargeMessage) { static const size_t INITIAL_CAPACITY=128; static const size_t MAX_CAPACITY= 1024; static const size_t MAX_RETURNED_MESSAGE_SIZE= 256; static const size_t INITIAL_POOL_SIZE= 4; static const size_t MAX_POOL_SIZE= 8; TestingLogMessagePool factory(INITIAL_CAPACITY, MAX_CAPACITY, MAX_RETURNED_MESSAGE_SIZE, INITIAL_POOL_SIZE, MAX_POOL_SIZE); std::vector<LogMessage*> messagesInPool; std::vector<LogMessage*> newMessagesInPool; LogMessage* msg; messagesInPool.reserve(INITIAL_POOL_SIZE); factory.getMessagesInPool(std::back_inserter(messagesInPool)); EXPECT_EQ(messagesInPool.size(), INITIAL_POOL_SIZE); msg= factory.get(); EXPECT_EQ(msg->capacity(), factory.initialMessageSize()); EXPECT_EQ(msg->maxCapacity(), factory.maxMessageSize()); EXPECT_TRUE(msg->empty()); // Verify the message came from the pool EXPECT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE-1); EXPECT_TRUE(std::find(messagesInPool.begin(), messagesInPool.end(), msg) != messagesInPool.end()); // Make the message too big to be returned to the pool msg->increaseCapacity(MAX_RETURNED_MESSAGE_SIZE+16); ASSERT_GT(msg->capacity(), MAX_RETURNED_MESSAGE_SIZE); // Verify the message destroyed upon release and not put back in the pool factory.release(msg); EXPECT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE-1); }
void AppenderFile::_write(LogMessage const& message) { bool exceedMaxSize = maxFileSize > 0 && (fileSize.value() + message.Size()) > maxFileSize; if (dynamicName) { char namebuf[TRINITY_PATH_MAX]; snprintf(namebuf, TRINITY_PATH_MAX, filename.c_str(), message.param1.c_str()); logfile = OpenFile(namebuf, mode, backup || exceedMaxSize); } else if (exceedMaxSize) logfile = OpenFile(filename, "w", true); if (!logfile) return; fprintf(logfile, "%s%s", message.prefix.c_str(), message.text.c_str()); fflush(logfile); fileSize += uint64(message.Size()); if (dynamicName) CloseFile(); }
void LogCategory::admitMessage(const LogMessage& message) const { processMessage(message); // If this is a fatal message, flush the handlers to make sure the log // message was written out, then crash. if (isLogLevelFatal(message.getLevel())) { auto numHandlers = db_->flushAllHandlers(); if (numHandlers == 0) { // No log handlers were configured. // Print the message to stderr, to make sure we always print the reason // we are crashing somewhere. auto msg = folly::to<std::string>( "FATAL:", message.getFileName(), ":", message.getLineNumber(), ": ", message.getMessage(), "\n"); folly::writeFull(STDERR_FILENO, msg.data(), msg.size()); } std::abort(); } }
std::string LogMessage::FullLogDetailsToString(const LogMessage& msg) { std::string out; out.append(msg.timestamp() + "\t" + msg.level() + " [" + msg.threadID() + " " + msg.file() + "->"+ msg.function() + ":" + msg.line() + "]\t"); return out; }
void Console::logToFile(const LogMessage& message) { #if defined __APPLE__ NSLogWrapper(message.string()); #else IO::FileManager fileManager; const String logDirectory = fileManager.logDirectory(); if (logDirectory.empty()) return; if (!fileManager.exists(logDirectory)) fileManager.makeDirectory(logDirectory); const String logFilePath = fileManager.appendPath(logDirectory, "TrenchBroom.log"); std::fstream logStream(logFilePath.c_str(), std::ios::out | std::ios::app); if (logStream.is_open()) { wxDateTime now = wxDateTime::Now(); logStream << wxGetProcessId() << " " << now.FormatISOCombined(' ') << ": " << message.string() << std::endl; } #endif }
void XMLLogger::write (LogMessage &log_message) { std::stringstream sstm; sstm << "\t<log id=\"" << log_message.get_id() << "\" level=\"" << log_message.get_level() << "\" file=\"" << log_message.get_file_name() << "\" function=\"" << log_message.get_function_name() << "\" line=\"" << log_message.get_line_number() << "\">\n\t\t" << log_message.get_text().c_str() << "\t\n\t</log>\n\n"; this->get_file() << sstm.str(); }
TEST(LogMessagePoolTests, ReleaseNonEmptyMessage) { static const size_t INITIAL_CAPACITY=128; static const size_t MAX_CAPACITY= 1024; static const size_t MAX_RETURNED_MESSAGE_SIZE= 256; static const size_t INITIAL_POOL_SIZE= 4; static const size_t MAX_POOL_SIZE= 8; TestingLogMessagePool factory(INITIAL_CAPACITY, MAX_CAPACITY, MAX_RETURNED_MESSAGE_SIZE, INITIAL_POOL_SIZE, MAX_POOL_SIZE); std::vector<LogMessage*> messages; LogMessage* msg; msg= factory.get(); EXPECT_EQ(msg->capacity(), factory.initialMessageSize()); EXPECT_EQ(msg->maxCapacity(), factory.maxMessageSize()); EXPECT_TRUE(msg->empty()); ASSERT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE-1); // Make the message not empty and return it to the pool msg->setEnd(msg->begin() + msg->capacity()/2); ASSERT_FALSE(msg->empty()); factory.release(msg); ASSERT_EQ(factory.numMessagesInPool(), INITIAL_POOL_SIZE); // Now get all messages in the pool, verify that one of them is msg, // and that all messages (including msg) are empty after leaving the pool for (int i=0;i<INITIAL_POOL_SIZE;++i) { messages.push_back(factory.get()); EXPECT_TRUE(messages.back()->empty()); } EXPECT_EQ(factory.numMessagesInPool(), 0); EXPECT_TRUE(std::find(messages.begin(), messages.end(), msg) != messages.end()); // Put everything back std::for_each(messages.begin(), messages.end(), [&factory](LogMessage* m) { factory.release(m); }); }
void Appender::write(LogMessage& message) { if (!level || level > message.level) { //fprintf(stderr, "Appender::write: Appender %s, Level %s. Msg %s Level %s Type %s WRONG LEVEL MASK\n", getName().c_str(), getLogLevelString(level), message.text.c_str(), getLogLevelString(message.level), getLogFilterTypeString(message.type)); // DEBUG - RemoveMe return; } message.prefix.clear(); if (flags & APPENDER_FLAGS_PREFIX_TIMESTAMP) message.prefix.append(message.getTimeStr().c_str()); if (flags & APPENDER_FLAGS_PREFIX_LOGLEVEL) { if (!message.prefix.empty()) message.prefix.push_back(' '); char text[MAX_QUERY_LEN]; snprintf(text, MAX_QUERY_LEN, "%-5s", Appender::getLogLevelString(message.level)); message.prefix.append(text); } if (flags & APPENDER_FLAGS_PREFIX_LOGFILTERTYPE) { if (!message.prefix.empty()) message.prefix.push_back(' '); char text[MAX_QUERY_LEN]; snprintf(text, MAX_QUERY_LEN, "[%s]", Appender::getLogFilterTypeString(message.type)); message.prefix.append(text); } if (!message.prefix.empty()) message.prefix.push_back(' '); _write(message); }
// helper for fatal LOG std::string fatalLogToString(const LogMessage& msg) { auto out = LogDetailsToString(msg); static const std::string fatalExitReason = {"EXIT trigger caused by LOG(FATAL) entry: "}; out.append("\n\t*******\t " + fatalExitReason + "\n\t" + '"' + msg.message() + '"'); return out; }
// helper for normal std::string normalToString(const LogMessage& msg) { auto out = LogDetailsToString(msg); out.append('"' + msg.message() + '"'); return out; }
// helper for setting the normal log details in an entry std::string LogDetailsToString(const LogMessage& msg) { std::string out; out.append("\n" + msg.timestamp() + " " + msg.microseconds() + "\t" + msg.level() + " [" + msg.file() + ":" + msg.line() + "]\t"); return out; }
std::string GlogStyleFormatter::formatMessage( const LogMessage& message, const LogCategory* /* handlerCategory */) { // Get the local time info struct tm ltime; auto timeSinceEpoch = message.getTimestamp().time_since_epoch(); auto epochSeconds = std::chrono::duration_cast<std::chrono::seconds>(timeSinceEpoch); std::chrono::microseconds usecs = std::chrono::duration_cast<std::chrono::microseconds>(timeSinceEpoch) - epochSeconds; time_t unixTimestamp = epochSeconds.count(); if (!localtime_r(&unixTimestamp, <ime)) { memset(<ime, 0, sizeof(ltime)); } auto basename = message.getFileBaseName(); auto headerFormatter = folly::format( "{}{:02d}{:02d} {:02d}:{:02d}:{:02d}.{:06d} {:5d} {}:{}] ", getGlogLevelName(message.getLevel())[0], ltime.tm_mon + 1, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec, usecs.count(), message.getThreadID(), basename, message.getLineNumber()); // TODO: Support including thread names and thread context info. // The fixed portion of the header takes up 31 bytes. // // The variable portions that we can't account for here include the line // number and the thread ID (just in case it is larger than 6 digits long). // Here we guess that 40 bytes will be long enough to include room for this. // // If this still isn't long enough the string will grow as necessary, so the // code will still be correct, but just slightly less efficient than if we // had allocated a large enough buffer the first time around. size_t headerLengthGuess = 40 + basename.size(); // Format the data into a buffer. std::string buffer; StringPiece msgData{message.getMessage()}; if (message.containsNewlines()) { // If there are multiple lines in the log message, add a header // before each one. std::string header; header.reserve(headerLengthGuess); headerFormatter.appendTo(header); // Make a guess at how many lines will be in the message, just to make an // initial buffer allocation. If the guess is too small then the string // will reallocate and grow as necessary, it will just be slightly less // efficient than if we had guessed enough space. size_t numLinesGuess = 4; buffer.reserve(((header.size() + 1) * numLinesGuess) + msgData.size()); size_t idx = 0; while (true) { auto end = msgData.find('\n', idx); if (end == StringPiece::npos) { end = msgData.size(); } buffer.append(header); auto line = msgData.subpiece(idx, end - idx); buffer.append(line.data(), line.size()); buffer.push_back('\n'); if (end == msgData.size()) { break; } idx = end + 1; } } else { buffer.reserve(headerLengthGuess + msgData.size()); headerFormatter.appendTo(buffer); buffer.append(msgData.data(), msgData.size()); buffer.push_back('\n'); } return buffer; }
void PlainFileLogger::logMessage(const std::string& type, const LogMessage& message) { std::stringstream ss; ss << message.getFileName() << " " << type << ": " << message.message << std::endl; logString(ss.str()); }
void on(LogMessage& value) { if (m_callback != 0) m_callback->LogMessage(value.getThreadId(), value.getTicks(), _bstr_t(value.getMessage().c_str())); }
void FileLogHandler::handle(const LogMessage & message) { std::ofstream logstream(m_logfile, std::ios_base::out | std::ios_base::app ); logstream << messagePrefix(message) << message.message() << std::endl; }
void LogFinisher::operator=(LogMessage& other) { other.Finish(); }
// helper for normal std::string LogMessage::normalToString(const LogMessage& msg) { auto out = msg._logDetailsToStringFunc(msg); out.append(msg.message() + '\n'); return out; }