| 1 | |
| 2 | // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide. |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, |
| 6 | // are permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, |
| 9 | // this list of conditions, and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, |
| 12 | // this list of conditions, and the following disclaimer in the documentation |
| 13 | // and/or other materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the names of the copyright holders nor the names of their contributors |
| 16 | // may be used to endorse or promote products derived from this software without |
| 17 | // specific prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT |
| 24 | // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
| 25 | // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR |
| 26 | // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 27 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS |
| 28 | // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES |
| 29 | // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE |
| 30 | // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES. |
| 31 | // |
| 32 | |
| 33 | #include "journalstackwalker.h" |
| 34 | #include "journaller.h" |
| 35 | #include "journalthreader.h" |
| 36 | #include "journalfile.h" |
| 37 | |
| 38 | #include <map> |
| 39 | #include <fstream> |
| 40 | #include <xstypes/xstime.h> |
| 41 | #include <xstypes/pstdint.h> // for PRINTF_INT64_MODIFIER |
| 42 | #include <xstypes/xsthread.h> // for xsGetCurrentThreadId |
| 43 | #include <xstypes/xstimestamp.h> |
| 44 | #include <xstypes/xstimeinfo.h> |
| 45 | #include <memory> |
| 46 | |
| 47 | #ifndef XSENS_NO_AUTOLIB |
| 48 | #pragma comment(lib, "psapi.lib") |
| 49 | #endif |
| 50 | |
| 51 | //! \brief The optional additional logger |
| 52 | AbstractAdditionalLogger* Journaller::m_additionalLogger = nullptr; |
| 53 | |
| 54 | inline int threadId() { |
| 55 | #if JOURNALLER_WITH_THREAD_SUPPORT && !defined(__APPLE__) |
| 56 | return (int) xsGetCurrentThreadId(); |
| 57 | #else |
| 58 | return 0; |
| 59 | #endif |
| 60 | } |
| 61 | |
| 62 | /*! \class Journaller |
| 63 | \brief A journalling class for debugging applications |
| 64 | |
| 65 | \details Create a Journaller object in your application or dll main and share it among the source files |
| 66 | of your application (ie by adding "extern Journaller* journal;" in the xscommon_config.h) |
| 67 | Use the supplied logging macros if you want to be able to remove the logging lines at compile-time. |
| 68 | |
| 69 | Multiple Journaller objects can use the same file |
| 70 | */ |
| 71 | |
| 72 | #if __GNUC__ >= 6 |
| 73 | // Ignore warning: nonnull argument ‘this’ compared to NULL [-Wnonnull-compare] |
| 74 | // This happens for the JL macro's which here have a this argument, which is always nonnull |
| 75 | // In the macros we compare this to NULL, which is now a warning in GCC6 |
| 76 | // On other locations, we do not use this for the macro, hence the warning does not show there |
| 77 | #pragma GCC diagnostic push |
| 78 | #pragma GCC diagnostic ignored "-Wnonnull-compare" |
| 79 | #endif |
| 80 | |
| 81 | /*! \brief Constructor |
| 82 | \details The constructor configures the object to use the specified file. If it is already open by |
| 83 | another Journaller object, the existing file is reused and it will not be purged. |
| 84 | \param pathfile The (path+) filename of the logfile to use |
| 85 | \param purge Whether to clear the logfile or append when opening the file (default true) |
| 86 | \param initialLogLevel The initial log level to use (default JLL_Alert) |
| 87 | */ |
| 88 | Journaller::Journaller(const XsString& pathfile, bool purge, JournalLogLevel initialLogLevel) |
| 89 | : m_file(nullptr) |
| 90 | , m_level(initialLogLevel) |
| 91 | , m_debugLevel(initialLogLevel) |
| 92 | , m_flushLevel(JLL_Alert) |
| 93 | , m_threader(new JournalThreader) |
| 94 | , m_useDateTime(false) |
| 95 | { |
| 96 | init(pathfile, purge); |
| 97 | } |
| 98 | |
| 99 | /*! \brief Destructor, detaches from the logfile and closes it if this was the last reference */ |
| 100 | Journaller::~Journaller() |
| 101 | { |
| 102 | } |
| 103 | |
| 104 | /*! \brief Initialize the Journaller by recreating the internal journal file */ |
| 105 | void Journaller::init(XsString const& pathfile, bool purge) |
| 106 | { |
| 107 | #ifdef ANDROID |
| 108 | setTag(tagFromFilename(pathfile.toStdString())); |
| 109 | #endif |
| 110 | m_file.reset(new JournalFile(pathfile, purge)); |
| 111 | } |
| 112 | |
| 113 | /*! \returns The tag string made from file name |
| 114 | \details This function is primarily useful on Android, where we always |
| 115 | need a tag set. |
| 116 | \param fn The file name string |
| 117 | */ |
| 118 | std::string Journaller::tagFromFilename(const std::string &fn) |
| 119 | { |
| 120 | const size_t b = fn.find_last_of("/") + 1; |
| 121 | const size_t l = fn.find_first_of("."); |
| 122 | return fn.substr(b, l - b); |
| 123 | } |
| 124 | |
| 125 | /*! \brief When setting the Date Time to \a yes, the timestamps are translated from unix timestamp into a redable date/time |
| 126 | \param yes The boolean value to set |
| 127 | \note the translation is not free, the recommended behaviour is to stick with the default unix timestamps |
| 128 | */ |
| 129 | void Journaller::setUseDateTime(bool yes) |
| 130 | { |
| 131 | m_useDateTime = yes; |
| 132 | } |
| 133 | |
| 134 | /*! \brief Sets the additional logger |
| 135 | \param[in] additionallogger A pointer (may be null) to the additional logger. |
| 136 | If additionalLogger is a null pointer, the current additionalLogger is removed. |
| 137 | \note Journaller does NOT take ownership of the logger. |
| 138 | */ |
| 139 | void Journaller::setAdditionalLogger(AbstractAdditionalLogger* additionallogger) |
| 140 | { |
| 141 | m_additionalLogger = additionallogger; |
| 142 | } |
| 143 | |
| 144 | /*! \brief A list of strings representing the different log levels, use JournalLogLevel to index */ |
| 145 | static const char* gLogLevelString[] = { |
| 146 | "[TRACE] ", |
| 147 | "[DEBUG] ", |
| 148 | "[ALERT] ", |
| 149 | "[ERROR] ", |
| 150 | "[FATAL] ", |
| 151 | "[WRITE] "}; |
| 152 | |
| 153 | /*! \brief Write a header for the log file including some meta-data about the journaller |
| 154 | */ |
| 155 | void Journaller::writeFileHeader(const std::string& appName) |
| 156 | { |
| 157 | m_appName = appName; |
| 158 | [[maybe_unused]] XsTimeStamp now = XsTimeStamp::now(); |
| 159 | JLWRITE(this, "Journaller logging to " << m_file->filename() << (appName.empty() ? XsString() : XsString(" for ") + appName) << " on " << now.toString()); |
| 160 | //JLWRITE(this, "Current log level is " << gLogLevelString[m_level]); |
| 161 | } |
| 162 | |
| 163 | /*! \brief Write a log message to the file if \a level is at least equal to the current log level |
| 164 | \param level The log level to use |
| 165 | \param msg The message to log |
| 166 | \details This function decorates \a msg with the time and log level and appends a newline |
| 167 | */ |
| 168 | void Journaller::log(JournalLogLevel level, const std::string& msg) |
| 169 | { |
| 170 | #ifdef ANDROID |
| 171 | __android_log_write(level, tag().c_str(), msg.c_str()); |
| 172 | #else |
| 173 | if (level < m_level && level < m_debugLevel) |
| 174 | return; |
| 175 | |
| 176 | m_threader->setLineLevel(threadId(), level); |
| 177 | writeTime(); |
| 178 | #if JOURNALLER_WITH_THREAD_SUPPORT |
| 179 | writeThread(); |
| 180 | #endif |
| 181 | writeTag(); |
| 182 | writeLevel(level); |
| 183 | writeMessage(msg); |
| 184 | writeMessage(std::string("\n")); |
| 185 | if (level >= m_flushLevel) |
| 186 | flush(); |
| 187 | #endif |
| 188 | } |
| 189 | |
| 190 | /*! \brief Write the current time to the file */ |
| 191 | void Journaller::writeTime() |
| 192 | { |
| 193 | XsTimeStamp ts = XsTimeStamp::now(); |
| 194 | if (!m_useDateTime) |
| 195 | { |
| 196 | // when using timestamp format we use UTC time! |
| 197 | char timebuf[32]; |
| 198 | sprintf(timebuf, "%10" PRINTF_INT64_MODIFIER "d.%03d ", ts.secondTime(), (int) ts.milliSecondPart()); |
| 199 | writeMessage(timebuf); |
| 200 | } |
| 201 | else |
| 202 | { |
| 203 | // when using date time format we use LOCAL time! |
| 204 | writeMessage(ts.utcToLocalTime().toString().toStdString()); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /*! \brief Write the current time to the file */ |
| 209 | void Journaller::writeThread() |
| 210 | { |
| 211 | char buf[32]; |
| 212 | #ifdef __GNUC__ |
| 213 | sprintf(buf, "<%08X> ", (unsigned int) threadId()); |
| 214 | #else |
| 215 | sprintf(buf, "<%04X> ", (unsigned int) threadId()); |
| 216 | #endif |
| 217 | writeMessage(buf); |
| 218 | } |
| 219 | |
| 220 | /*! \brief Write the tag to the file */ |
| 221 | void Journaller::writeTag() |
| 222 | { |
| 223 | std::string tmp = tag(); |
| 224 | if (!tmp.empty()) |
| 225 | writeMessage(tmp); |
| 226 | } |
| 227 | |
| 228 | /*! \brief Write the supplied log \a level to the file |
| 229 | \param level The log level to set |
| 230 | \note This does not actually CHANGE the log level of the line to the supplied value |
| 231 | */ |
| 232 | void Journaller::writeLevel(JournalLogLevel level) |
| 233 | { |
| 234 | writeMessage(std::string(gLogLevelString[level])); |
| 235 | } |
| 236 | |
| 237 | /*! \brief Write \a msg to the file without decoration or added newline |
| 238 | \param msg The message to write |
| 239 | \details This function is also used to do the actual writing. It will only write the data to the |
| 240 | outputs when the end of \a msg is a newline character, otherwise it will queue \a msg to be |
| 241 | written later. If \a msg is empty, the currently queued data is written immediately |
| 242 | */ |
| 243 | void Journaller::writeMessage(const std::string& msg) |
| 244 | { |
| 245 | if (msg.empty()) |
| 246 | { |
| 247 | flushLine(); |
| 248 | return; |
| 249 | } |
| 250 | |
| 251 | m_threader->line(threadId()).append(msg); |
| 252 | char eol = *msg.rbegin(); |
| 253 | if (eol == '\n' || eol == '\r') |
| 254 | flushLine(); |
| 255 | } |
| 256 | |
| 257 | /*! \brief Flush any data currently queued for logging to the file buffer |
| 258 | */ |
| 259 | void Journaller::flushLine() |
| 260 | { |
| 261 | int thread = threadId(); |
| 262 | std::string& line = m_threader->line(thread); |
| 263 | JournalLogLevel lineLevel = m_threader->lineLevel(thread); |
| 264 | if (!line.empty()) |
| 265 | { |
| 266 | if (lineLevel >= m_level) |
| 267 | m_threader->writeLine(thread, m_file.get()); |
| 268 | if (lineLevel > m_debugLevel) |
| 269 | m_threader->writeLine(thread, nullptr); |
| 270 | line.clear(); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /*! \brief Flush any data to disk */ |
| 275 | void Journaller::flush() |
| 276 | { |
| 277 | if (m_file) |
| 278 | { |
| 279 | flushLine(); |
| 280 | m_file->flush(); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /*! \brief Set level threshold for automatically flushing lines to disk. */ |
| 285 | void Journaller::setFlushLevel(JournalLogLevel level, bool writeLogLine) |
| 286 | { |
| 287 | m_flushLevel = level; |
| 288 | if (writeLogLine) |
| 289 | JLGENERIC(this, JLL_Write, "Flush level switched to " << gLogLevelString[m_flushLevel]); |
| 290 | } |
| 291 | |
| 292 | /*! \brief Write the current callstack to the file if \a level is at least equal to the current log level |
| 293 | */ |
| 294 | void Journaller::writeCallstack(JournalLogLevel level) |
| 295 | { |
| 296 | if (level < m_level) |
| 297 | return; |
| 298 | |
| 299 | JLGENERIC(this, level, "************ Dump Begin ************"); |
| 300 | JournalStackWalker sw(this); |
| 301 | sw.ShowCallstack(); |
| 302 | JLGENERIC(this, level, "************* Dump End *************"); |
| 303 | } |
| 304 | |
| 305 | /*! \brief Set the log level for logging to file |
| 306 | \param level The log level to use |
| 307 | \param writeLogLine If set to true then it writes a log line |
| 308 | \details Any log requests of a lower level will not be done |
| 309 | */ |
| 310 | void Journaller::setLogLevel(JournalLogLevel level, bool writeLogLine) |
| 311 | { |
| 312 | m_level = level; |
| 313 | if (writeLogLine) |
| 314 | JLGENERIC(this, JLL_Write, "Log level set to " << gLogLevelString[level]); |
| 315 | } |
| 316 | |
| 317 | /*! \brief Set the log level for logging to debug output |
| 318 | \param level The log level to use |
| 319 | \param writeLogLine If set to true then it writes a log line |
| 320 | \details Any log requests of a lower level will not be done |
| 321 | */ |
| 322 | void Journaller::setDebugLevel(JournalLogLevel level, bool writeLogLine) |
| 323 | { |
| 324 | m_debugLevel = level; |
| 325 | if (writeLogLine) |
| 326 | JLGENERIC(this, JLL_Write, "Debugger output log level set to " << gLogLevelString[level]); |
| 327 | } |
| 328 | |
| 329 | /*! \brief Returns the filename of the used journal file */ |
| 330 | const XsString Journaller::filename() const |
| 331 | { |
| 332 | return m_file->filename(); |
| 333 | } |
| 334 | |
| 335 | /*! \brief Set a tag to be added before the log level tag in each log file |
| 336 | */ |
| 337 | void Journaller::setTag(const std::string &tag) |
| 338 | { |
| 339 | m_tag = tag; |
| 340 | } |
| 341 | |
| 342 | /*! \returns a tag that will be added before the log level tag in each log file. |
| 343 | \details On most platforms the default tag is an empty string, on |
| 344 | Android it defaults to the filename without extension to be able to |
| 345 | make full use of the logcat backend. |
| 346 | |
| 347 | Override the tag using setTag, or overload this function. |
| 348 | */ |
| 349 | std::string Journaller::tag() const |
| 350 | { |
| 351 | return m_tag; |
| 352 | } |
| 353 | |
| 354 | template <> |
| 355 | std::ostream& operator << (std::ostream& os, JlHexLogger<char> const& hex) |
| 356 | { |
| 357 | return os << JlHexLogger<int>((int) hex.m_value); |
| 358 | } |
| 359 | |
| 360 | /*! \brief Move the log file to the supplied path, keeping current contents intact |
| 361 | \param pathfile The path of a file to change to |
| 362 | \param purge If set to true (default) then it clears the log file that we changed to |
| 363 | \param eraseOld If set to true (default) then the old log file will be removed |
| 364 | */ |
| 365 | void Journaller::moveLogFile(const XsString& pathfile, bool purge, bool eraseOld) |
| 366 | { |
| 367 | if (m_file && m_file->filename() == pathfile) |
| 368 | return; |
| 369 | |
| 370 | JournalFile* newFile = new JournalFile(pathfile, purge); |
| 371 | |
| 372 | XsString oldFileName; |
| 373 | std::unique_ptr<uint8_t[]> buffer; |
| 374 | XsFilePos sz = 0; |
| 375 | if (m_file && m_file->xsFile().isOpen()) |
| 376 | { |
| 377 | oldFileName = m_file->filename(); |
| 378 | JLWRITE(this, "Switching to file " << pathfile); |
| 379 | |
| 380 | XsFile& file = m_file->xsFile(); |
| 381 | sz = file.tell(); |
| 382 | if (sz) |
| 383 | { |
| 384 | file.seek(0); |
| 385 | buffer.reset(new uint8_t[(int)sz]); |
| 386 | sz = file.read(buffer.get(), 1, sz); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | m_file.reset(newFile); |
| 391 | if (buffer && sz) |
| 392 | m_file->xsFile().write(buffer.get(), 1, sz); |
| 393 | else |
| 394 | writeFileHeader(m_appName); |
| 395 | |
| 396 | if (!oldFileName.empty()) |
| 397 | { |
| 398 | if (eraseOld) |
| 399 | _unlink(oldFileName.c_str()); |
| 400 | JLDEBUG(this, "Switched from " << oldFileName << " to " << pathfile); |
| 401 | } |
| 402 | else |
| 403 | JLDEBUG(this, "Switched to " << pathfile); |
| 404 | } |
| 405 | |
| 406 | /*! \brief Copy the contents of the current log file to \a target |
| 407 | \details After copying the contents, the current log file is closed. |
| 408 | \param target The destination Journaller to write to |
| 409 | \param eraseOld When true (default), the old log file is deleted |
| 410 | */ |
| 411 | void Journaller::moveLogs(Journaller* target, bool eraseOld) |
| 412 | { |
| 413 | assert(target); |
| 414 | if (target->filename() == filename()) |
| 415 | return; |
| 416 | |
| 417 | auto newFile = target->m_file; |
| 418 | XsString oldFileName; |
| 419 | std::unique_ptr<uint8_t[]> buffer; |
| 420 | XsFilePos sz = 0; |
| 421 | if (m_file && m_file->xsFile().isOpen()) |
| 422 | { |
| 423 | oldFileName = m_file->filename(); |
| 424 | JLDEBUG(target, "************ Moving logs from " << oldFileName << " to " << target->filename()); |
| 425 | |
| 426 | XsFile& file = m_file->xsFile(); |
| 427 | sz = file.tell(); |
| 428 | if (sz) |
| 429 | { |
| 430 | file.seek(0); |
| 431 | buffer.reset(new uint8_t[(int)sz]); |
| 432 | sz = file.read(buffer.get(), 1, sz); |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | if (buffer && sz && newFile) |
| 437 | newFile->xsFile().write(buffer.get(), 1, sz); |
| 438 | m_file = newFile; |
| 439 | |
| 440 | if (!oldFileName.empty()) |
| 441 | { |
| 442 | if (eraseOld) |
| 443 | _unlink(oldFileName.c_str()); |
| 444 | JLDEBUG(target, "************ Moved logs from " << oldFileName); |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /*! \brief Cleans up any remaining stuff |
| 449 | \details The function assumes that no new log lines will be created anymore |
| 450 | \param gj Optional pointer to Journaller pointer to be cleaned up, usually &gJournal should be provided. The pointer that gj points to will be set to nullptr. |
| 451 | \note JLINSTALLQTDEBUGHANDLER(0) is not done as it would create a dependency on Qt so you need to call that yourself before calling jlTerminate |
| 452 | */ |
| 453 | void jlTerminate(Journaller** gj) |
| 454 | { |
| 455 | if (gj && *gj) |
| 456 | { |
| 457 | delete *gj; |
| 458 | *gj = nullptr; |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | #if __GNUC__ >= 6 |
| 463 | #pragma GCC diagnostic pop |
| 464 | #endif |