logging.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef TENSORRT_LOGGING_H
  17. #define TENSORRT_LOGGING_H
  18. #include "NvInferRuntimeCommon.h"
  19. #include <cassert>
  20. #include <ctime>
  21. #include <iomanip>
  22. #include <iostream>
  23. #include <ostream>
  24. #include <sstream>
  25. #include <string>
  26. #include "macros.h"
  27. using Severity = nvinfer1::ILogger::Severity;
  28. namespace gsd{
  29. class LogStreamConsumerBuffer : public std::stringbuf
  30. {
  31. public:
  32. LogStreamConsumerBuffer(std::ostream& stream, const std::string& prefix, bool shouldLog)
  33. : mOutput(stream)
  34. , mPrefix(prefix)
  35. , mShouldLog(shouldLog)
  36. {
  37. }
  38. LogStreamConsumerBuffer(LogStreamConsumerBuffer&& other)
  39. : mOutput(other.mOutput)
  40. {
  41. }
  42. ~LogStreamConsumerBuffer()
  43. {
  44. // std::streambuf::pbase() gives a pointer to the beginning of the buffered part of the output sequence
  45. // std::streambuf::pptr() gives a pointer to the current position of the output sequence
  46. // if the pointer to the beginning is not equal to the pointer to the current position,
  47. // call putOutput() to log the output to the stream
  48. if (pbase() != pptr())
  49. {
  50. putOutput();
  51. }
  52. }
  53. // synchronizes the stream buffer and returns 0 on success
  54. // synchronizing the stream buffer consists of inserting the buffer contents into the stream,
  55. // resetting the buffer and flushing the stream
  56. virtual int sync()
  57. {
  58. putOutput();
  59. return 0;
  60. }
  61. void putOutput()
  62. {
  63. if (mShouldLog)
  64. {
  65. // prepend timestamp
  66. std::time_t timestamp = std::time(nullptr);
  67. tm* tm_local = std::localtime(&timestamp);
  68. std::cout << "[";
  69. std::cout << std::setw(2) << std::setfill('0') << 1 + tm_local->tm_mon << "/";
  70. std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_mday << "/";
  71. std::cout << std::setw(4) << std::setfill('0') << 1900 + tm_local->tm_year << "-";
  72. std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_hour << ":";
  73. std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_min << ":";
  74. std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_sec << "] ";
  75. // std::stringbuf::str() gets the string contents of the buffer
  76. // insert the buffer contents pre-appended by the appropriate prefix into the stream
  77. mOutput << mPrefix << str();
  78. // set the buffer to empty
  79. str("");
  80. // flush the stream
  81. mOutput.flush();
  82. }
  83. }
  84. void setShouldLog(bool shouldLog)
  85. {
  86. mShouldLog = shouldLog;
  87. }
  88. private:
  89. std::ostream& mOutput;
  90. std::string mPrefix;
  91. bool mShouldLog;
  92. };
  93. //!
  94. //! \class LogStreamConsumerBase
  95. //! \brief Convenience object used to initialize LogStreamConsumerBuffer before std::ostream in LogStreamConsumer
  96. //!
  97. class LogStreamConsumerBase
  98. {
  99. public:
  100. LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog)
  101. : mBuffer(stream, prefix, shouldLog)
  102. {
  103. }
  104. protected:
  105. LogStreamConsumerBuffer mBuffer;
  106. };
  107. //!
  108. //! \class LogStreamConsumer
  109. //! \brief Convenience object used to facilitate use of C++ stream syntax when logging messages.
  110. //! Order of base classes is LogStreamConsumerBase and then std::ostream.
  111. //! This is because the LogStreamConsumerBase class is used to initialize the LogStreamConsumerBuffer member field
  112. //! in LogStreamConsumer and then the address of the buffer is passed to std::ostream.
  113. //! This is necessary to prevent the address of an uninitialized buffer from being passed to std::ostream.
  114. //! Please do not change the order of the parent classes.
  115. //!
  116. class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream
  117. {
  118. public:
  119. //! \brief Creates a LogStreamConsumer which logs messages with level severity.
  120. //! Reportable severity determines if the messages are severe enough to be logged.
  121. LogStreamConsumer(Severity reportableSeverity, Severity severity)
  122. : LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity)
  123. , std::ostream(&mBuffer) // links the stream buffer with the stream
  124. , mShouldLog(severity <= reportableSeverity)
  125. , mSeverity(severity)
  126. {
  127. }
  128. LogStreamConsumer(LogStreamConsumer&& other)
  129. : LogStreamConsumerBase(severityOstream(other.mSeverity), severityPrefix(other.mSeverity), other.mShouldLog)
  130. , std::ostream(&mBuffer) // links the stream buffer with the stream
  131. , mShouldLog(other.mShouldLog)
  132. , mSeverity(other.mSeverity)
  133. {
  134. }
  135. void setReportableSeverity(Severity reportableSeverity)
  136. {
  137. mShouldLog = mSeverity <= reportableSeverity;
  138. mBuffer.setShouldLog(mShouldLog);
  139. }
  140. private:
  141. static std::ostream& severityOstream(Severity severity)
  142. {
  143. return severity >= Severity::kINFO ? std::cout : std::cerr;
  144. }
  145. static std::string severityPrefix(Severity severity)
  146. {
  147. switch (severity)
  148. {
  149. case Severity::kINTERNAL_ERROR: return "[F] ";
  150. case Severity::kERROR: return "[E] ";
  151. case Severity::kWARNING: return "[W] ";
  152. case Severity::kINFO: return "[I] ";
  153. case Severity::kVERBOSE: return "[V] ";
  154. default: assert(0); return "";
  155. }
  156. }
  157. bool mShouldLog;
  158. Severity mSeverity;
  159. };
  160. //! \class Logger
  161. //!
  162. //! \brief Class which manages logging of TensorRT tools and samples
  163. //!
  164. //! \details This class provides a common interface for TensorRT tools and samples to log information to the console,
  165. //! and supports logging two types of messages:
  166. //!
  167. //! - Debugging messages with an associated severity (info, warning, error, or internal error/fatal)
  168. //! - Test pass/fail messages
  169. //!
  170. //! The advantage of having all samples use this class for logging as opposed to emitting directly to stdout/stderr is
  171. //! that the logic for controlling the verbosity and formatting of sample output is centralized in one location.
  172. //!
  173. //! In the future, this class could be extended to support dumping test results to a file in some standard format
  174. //! (for example, JUnit XML), and providing additional metadata (e.g. timing the duration of a test run).
  175. //!
  176. //! TODO: For backwards compatibility with existing samples, this class inherits directly from the nvinfer1::ILogger
  177. //! interface, which is problematic since there isn't a clean separation between messages coming from the TensorRT
  178. //! library and messages coming from the sample.
  179. //!
  180. //! In the future (once all samples are updated to use Logger::getTRTLogger() to access the ILogger) we can refactor the
  181. //! class to eliminate the inheritance and instead make the nvinfer1::ILogger implementation a member of the Logger
  182. //! object.
  183. class Logger : public nvinfer1::ILogger
  184. {
  185. public:
  186. Logger(Severity severity = Severity::kWARNING)
  187. : mReportableSeverity(severity)
  188. {
  189. }
  190. //!
  191. //! \enum TestResult
  192. //! \brief Represents the state of a given test
  193. //!
  194. enum class TestResult
  195. {
  196. kRUNNING, //!< The test is running
  197. kPASSED, //!< The test passed
  198. kFAILED, //!< The test failed
  199. kWAIVED //!< The test was waived
  200. };
  201. //!
  202. //! \brief Forward-compatible method for retrieving the nvinfer::ILogger associated with this Logger
  203. //! \return The nvinfer1::ILogger associated with this Logger
  204. //!
  205. //! TODO Once all samples are updated to use this method to register the logger with TensorRT,
  206. //! we can eliminate the inheritance of Logger from ILogger
  207. //!
  208. nvinfer1::ILogger& getTRTLogger()
  209. {
  210. return *this;
  211. }
  212. //!
  213. //! \brief Implementation of the nvinfer1::ILogger::log() virtual method
  214. //!
  215. //! Note samples should not be calling this function directly; it will eventually go away once we eliminate the
  216. //! inheritance from nvinfer1::ILogger
  217. //!
  218. void log(Severity severity, const char* msg) TRT_NOEXCEPT override
  219. {
  220. LogStreamConsumer(mReportableSeverity, severity) << "[TRT] " << std::string(msg) << std::endl;
  221. }
  222. //!
  223. //! \brief Method for controlling the verbosity of logging output
  224. //!
  225. //! \param severity The logger will only emit messages that have severity of this level or higher.
  226. //!
  227. void setReportableSeverity(Severity severity)
  228. {
  229. mReportableSeverity = severity;
  230. }
  231. //!
  232. //! \brief Opaque handle that holds logging information for a particular test
  233. //!
  234. //! This object is an opaque handle to information used by the Logger to print test results.
  235. //! The sample must call Logger::defineTest() in order to obtain a TestAtom that can be used
  236. //! with Logger::reportTest{Start,End}().
  237. //!
  238. class TestAtom
  239. {
  240. public:
  241. TestAtom(TestAtom&&) = default;
  242. private:
  243. friend class Logger;
  244. TestAtom(bool started, const std::string& name, const std::string& cmdline)
  245. : mStarted(started)
  246. , mName(name)
  247. , mCmdline(cmdline)
  248. {
  249. }
  250. bool mStarted;
  251. std::string mName;
  252. std::string mCmdline;
  253. };
  254. //!
  255. //! \brief Define a test for logging
  256. //!
  257. //! \param[in] name The name of the test. This should be a string starting with
  258. //! "TensorRT" and containing dot-separated strings containing
  259. //! the characters [A-Za-z0-9_].
  260. //! For example, "TensorRT.sample_googlenet"
  261. //! \param[in] cmdline The command line used to reproduce the test
  262. //
  263. //! \return a TestAtom that can be used in Logger::reportTest{Start,End}().
  264. //!
  265. static TestAtom defineTest(const std::string& name, const std::string& cmdline)
  266. {
  267. return TestAtom(false, name, cmdline);
  268. }
  269. //!
  270. //! \brief A convenience overloaded version of defineTest() that accepts an array of command-line arguments
  271. //! as input
  272. //!
  273. //! \param[in] name The name of the test
  274. //! \param[in] argc The number of command-line arguments
  275. //! \param[in] argv The array of command-line arguments (given as C strings)
  276. //!
  277. //! \return a TestAtom that can be used in Logger::reportTest{Start,End}().
  278. static TestAtom defineTest(const std::string& name, int argc, char const* const* argv)
  279. {
  280. auto cmdline = genCmdlineString(argc, argv);
  281. return defineTest(name, cmdline);
  282. }
  283. //!
  284. //! \brief Report that a test has started.
  285. //!
  286. //! \pre reportTestStart() has not been called yet for the given testAtom
  287. //!
  288. //! \param[in] testAtom The handle to the test that has started
  289. //!
  290. static void reportTestStart(TestAtom& testAtom)
  291. {
  292. reportTestResult(testAtom, TestResult::kRUNNING);
  293. assert(!testAtom.mStarted);
  294. testAtom.mStarted = true;
  295. }
  296. //!
  297. //! \brief Report that a test has ended.
  298. //!
  299. //! \pre reportTestStart() has been called for the given testAtom
  300. //!
  301. //! \param[in] testAtom The handle to the test that has ended
  302. //! \param[in] result The result of the test. Should be one of TestResult::kPASSED,
  303. //! TestResult::kFAILED, TestResult::kWAIVED
  304. //!
  305. static void reportTestEnd(const TestAtom& testAtom, TestResult result)
  306. {
  307. assert(result != TestResult::kRUNNING);
  308. assert(testAtom.mStarted);
  309. reportTestResult(testAtom, result);
  310. }
  311. static int reportPass(const TestAtom& testAtom)
  312. {
  313. reportTestEnd(testAtom, TestResult::kPASSED);
  314. return EXIT_SUCCESS;
  315. }
  316. static int reportFail(const TestAtom& testAtom)
  317. {
  318. reportTestEnd(testAtom, TestResult::kFAILED);
  319. return EXIT_FAILURE;
  320. }
  321. static int reportWaive(const TestAtom& testAtom)
  322. {
  323. reportTestEnd(testAtom, TestResult::kWAIVED);
  324. return EXIT_SUCCESS;
  325. }
  326. static int reportTest(const TestAtom& testAtom, bool pass)
  327. {
  328. return pass ? reportPass(testAtom) : reportFail(testAtom);
  329. }
  330. Severity getReportableSeverity() const
  331. {
  332. return mReportableSeverity;
  333. }
  334. private:
  335. //!
  336. //! \brief returns an appropriate string for prefixing a log message with the given severity
  337. //!
  338. static const char* severityPrefix(Severity severity)
  339. {
  340. switch (severity)
  341. {
  342. case Severity::kINTERNAL_ERROR: return "[F] ";
  343. case Severity::kERROR: return "[E] ";
  344. case Severity::kWARNING: return "[W] ";
  345. case Severity::kINFO: return "[I] ";
  346. case Severity::kVERBOSE: return "[V] ";
  347. default: assert(0); return "";
  348. }
  349. }
  350. //!
  351. //! \brief returns an appropriate string for prefixing a test result message with the given result
  352. //!
  353. static const char* testResultString(TestResult result)
  354. {
  355. switch (result)
  356. {
  357. case TestResult::kRUNNING: return "RUNNING";
  358. case TestResult::kPASSED: return "PASSED";
  359. case TestResult::kFAILED: return "FAILED";
  360. case TestResult::kWAIVED: return "WAIVED";
  361. default: assert(0); return "";
  362. }
  363. }
  364. //!
  365. //! \brief returns an appropriate output stream (cout or cerr) to use with the given severity
  366. //!
  367. static std::ostream& severityOstream(Severity severity)
  368. {
  369. return severity >= Severity::kINFO ? std::cout : std::cerr;
  370. }
  371. //!
  372. //! \brief method that implements logging test results
  373. //!
  374. static void reportTestResult(const TestAtom& testAtom, TestResult result)
  375. {
  376. severityOstream(Severity::kINFO) << "&&&& " << testResultString(result) << " " << testAtom.mName << " # "
  377. << testAtom.mCmdline << std::endl;
  378. }
  379. //!
  380. //! \brief generate a command line string from the given (argc, argv) values
  381. //!
  382. static std::string genCmdlineString(int argc, char const* const* argv)
  383. {
  384. std::stringstream ss;
  385. for (int i = 0; i < argc; i++)
  386. {
  387. if (i > 0)
  388. ss << " ";
  389. ss << argv[i];
  390. }
  391. return ss.str();
  392. }
  393. Severity mReportableSeverity;
  394. };
  395. namespace
  396. {
  397. // //!
  398. // //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kVERBOSE
  399. // //!
  400. // //! Example usage:
  401. // //!
  402. // //! LOG_VERBOSE(logger) << "hello world" << std::endl;
  403. // //!
  404. // inline LogStreamConsumer LOG_VERBOSE(const Logger& logger)
  405. // {
  406. // return LogStreamConsumer(logger.getReportableSeverity(), Severity::kVERBOSE);
  407. // }
  408. // //!
  409. // //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINFO
  410. // //!
  411. // //! Example usage:
  412. // //!
  413. // //! LOG_INFO(logger) << "hello world" << std::endl;
  414. // //!
  415. // inline LogStreamConsumer LOG_INFO(const Logger& logger)
  416. // {
  417. // return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINFO);
  418. // }
  419. // //!
  420. // //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kWARNING
  421. // //!
  422. // //! Example usage:
  423. // //!
  424. // //! LOG_WARN(logger) << "hello world" << std::endl;
  425. // //!
  426. // inline LogStreamConsumer LOG_WARN(const Logger& logger)
  427. // {
  428. // return LogStreamConsumer(logger.getReportableSeverity(), Severity::kWARNING);
  429. // }
  430. // //!
  431. // //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kERROR
  432. // //!
  433. // //! Example usage:
  434. // //!
  435. // //! LOG_ERROR(logger) << "hello world" << std::endl;
  436. // //!
  437. // inline LogStreamConsumer LOG_ERROR(const Logger& logger)
  438. // {
  439. // return LogStreamConsumer(logger.getReportableSeverity(), Severity::kERROR);
  440. // }
  441. // //!
  442. // //! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINTERNAL_ERROR
  443. // // ("fatal" severity)
  444. // //!
  445. // //! Example usage:
  446. // //!
  447. // //! LOG_FATAL(logger) << "hello world" << std::endl;
  448. // //!
  449. // inline LogStreamConsumer LOG_FATAL(const Logger& logger)
  450. // {
  451. // return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINTERNAL_ERROR);
  452. // }
  453. } // anonymous namespace
  454. }
  455. #endif // TENSORRT_LOGGING_H