logging.h 16 KB

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