carl  24.04
Computer ARithmetic Library
Sink.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <fstream>
4 #include <ostream>
5 
6 namespace carl::logging {
7 
8 /**
9  * Base class for a logging sink. It only provides an interface to access some std::ostream.
10  */
11 class Sink {
12 public:
13  /**
14  * Abstract logging interface.
15  * The intended usage is to write any log output to the output stream returned by this function.
16  * @return Output stream.
17  */
18  virtual std::ostream& log() noexcept = 0;
19 };
20 /**
21  * Logging sink that wraps an arbitrary `std::ostream`.
22  * It is meant to be used for streams like `std::cout` or `std::cerr`.
23  */
24 class StreamSink final: public Sink {
25  /// Output stream.
26  std::ostream os;
27 public:
28  /**
29  * Create a StreamSink from some output stream.
30  * @param _os Output stream.
31  */
32  explicit StreamSink(std::ostream& _os): os(_os.rdbuf()) {}
33  std::ostream& log() noexcept override { return os; }
34 };
35 /**
36  * Logging sink for file output.
37  */
38 class FileSink: public Sink {
39  /// File output stream.
40  std::ofstream os;
41 public:
42  virtual ~FileSink() = default;
43  /**
44  * Create a FileSink that logs to the specified file.
45  * The file is truncated upon construction.
46  * @param filename
47  */
48  explicit FileSink(const std::string& filename): os(filename, std::ios::out) {}
49  std::ostream& log() noexcept override { return os; }
50 };
51 
52 }
Contains a custom logging facility.
Definition: carl-logging.cpp:6
Base class for a logging sink.
Definition: Sink.h:11
virtual std::ostream & log() noexcept=0
Abstract logging interface.
Logging sink that wraps an arbitrary std::ostream.
Definition: Sink.h:24
std::ostream os
Output stream.
Definition: Sink.h:26
std::ostream & log() noexcept override
Abstract logging interface.
Definition: Sink.h:33
StreamSink(std::ostream &_os)
Create a StreamSink from some output stream.
Definition: Sink.h:32
Logging sink for file output.
Definition: Sink.h:38
std::ofstream os
File output stream.
Definition: Sink.h:40
std::ostream & log() noexcept override
Abstract logging interface.
Definition: Sink.h:49
FileSink(const std::string &filename)
Create a FileSink that logs to the specified file.
Definition: Sink.h:48
virtual ~FileSink()=default