You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.2 KiB

2 months ago
  1. /**
  2. * @file sink.h
  3. *
  4. * Defines classes for log sinks (i.e. outputs)
  5. */
  6. #pragma once
  7. #include <ostream>
  8. #include <fstream>
  9. namespace l3pp {
  10. /**
  11. * Base class for a logging sink. It can only log some log entry to which some
  12. * formatting is applied (see Formatter). A Sink may be given a log level,
  13. * which filters out all entries below that level. By default is logs all
  14. * entries.
  15. */
  16. class Sink {
  17. LogLevel level;
  18. FormatterPtr formatter;
  19. virtual void logEntry(std::string const& entry) const = 0;
  20. public:
  21. Sink() : level(LogLevel::ALL), formatter(std::make_shared<Formatter>()) {
  22. }
  23. Sink(FormatterPtr formatter) : level(LogLevel::ALL), formatter(formatter) {
  24. }
  25. /**
  26. * Default destructor.
  27. */
  28. virtual ~Sink() {}
  29. LogLevel getLevel() const {
  30. return level;
  31. }
  32. void setLevel(LogLevel level) {
  33. this->level = level;
  34. }
  35. FormatterPtr getFormatter() const {
  36. return formatter;
  37. }
  38. void setFormatter(FormatterPtr formatter) {
  39. this->formatter = formatter;
  40. }
  41. /**
  42. * Logs the given message with context info
  43. */
  44. void log(EntryContext const& context, std::string const& message) const;
  45. };
  46. typedef std::shared_ptr<Sink> SinkPtr;
  47. /**
  48. * Logging sink that wraps an arbitrary `std::ostream`.
  49. * It is meant to be used for streams like `std::cout` or `std::cerr`.
  50. */
  51. class StreamSink: public Sink {
  52. /// Output stream.
  53. mutable std::ostream os;
  54. void logEntry(std::string const& entry) const override {
  55. os << entry << std::flush;
  56. }
  57. explicit StreamSink(std::ostream& _os) :
  58. os(_os.rdbuf()) {}
  59. public:
  60. /**
  61. * Create a StreamSink from some output stream.
  62. * @param os Output stream.
  63. */
  64. static SinkPtr create(std::ostream& os) {
  65. return SinkPtr(new StreamSink(os));
  66. }
  67. };
  68. /**
  69. * Logging sink for file output.
  70. */
  71. class FileSink: public Sink {
  72. /// File output stream.
  73. mutable std::ofstream os;
  74. void logEntry(std::string const& entry) const override {
  75. os << entry << std::flush;
  76. }
  77. explicit FileSink(const std::string& filename) :
  78. os(filename, std::ios::out) {}
  79. public:
  80. /**
  81. * Create a FileSink that logs to the specified file.
  82. * The file is truncated upon construction.
  83. * @param filename
  84. */
  85. static SinkPtr create(const std::string& filename) {
  86. return SinkPtr(new FileSink(filename));
  87. }
  88. };
  89. }