vlog.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_VLOG_H_
  5. #define CARBON_COMMON_VLOG_H_
  6. #include "common/ostream.h"
  7. #include "common/template_string.h"
  8. #include "llvm/Support/FormatVariadic.h"
  9. namespace Carbon::Internal {
  10. // Implements verbose logging.
  11. //
  12. // This is designed to minimize the overhead in callers by being a
  13. // forcibly-outlined routine that takes a minimal number of parameters.
  14. //
  15. // Internally uses `llvm::formatv` to render the format string with any value
  16. // arguments, and streams the result to the provided stream.
  17. template <TemplateString FormatStr, typename... Ts>
  18. [[clang::noinline]] auto VLogImpl(llvm::raw_ostream* stream, Ts&&... values)
  19. -> void {
  20. *stream << llvm::formatv(FormatStr.c_str(), std::forward<Ts>(values)...);
  21. }
  22. } // namespace Carbon::Internal
  23. // Logs when verbose logging is enabled. CARBON_VLOG_TO uses a provided stream;
  24. // CARBON_VLOG requires a member named `vlog_stream_`.
  25. //
  26. // For example:
  27. // CARBON_VLOG_TO(vlog_stream, "Verbose message: {0}", "extra information");
  28. // CARBON_VLOG("Verbose message: {0}", "extra information");
  29. //
  30. // The first argument must be a string literal format string valid for passing
  31. // to `llvm::formatv`. If it contains any substitutions, those should be passed
  32. // as subsequent arguments.
  33. //
  34. // Also supports a legacy syntax where no arguments are passed and the desired
  35. // logging is streamed into the call:
  36. // CARBON_VLOG() << "Legacy verbose message";
  37. //
  38. // However, the streaming syntax has higher overhead and can inhibit inlining.
  39. // Code should prefer the format string form, and eventually when all code has
  40. // migrated the streaming interface will be removed.
  41. #define CARBON_VLOG_TO(Stream, FormatStr, ...) \
  42. __builtin_expect(Stream == nullptr, true) \
  43. ? (void)0 \
  44. : Carbon::Internal::VLogImpl<"" FormatStr>(Stream __VA_OPT__(, ) \
  45. __VA_ARGS__)
  46. #define CARBON_VLOG(FormatStr, ...) \
  47. CARBON_VLOG_TO(vlog_stream_, FormatStr, __VA_ARGS__)
  48. #endif // CARBON_COMMON_VLOG_H_