plugin  0.1.0
slog.hpp
1 // Copyright (C) 2018-2024 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4 
10 #pragma once
11 
12 #include <iostream>
13 #include <string>
14 
15 namespace slog {
16 
21 class LogStreamEndLine { };
22 
23 static constexpr LogStreamEndLine endl;
24 
25 
31 
32 static constexpr LogStreamBoolAlpha boolalpha;
33 
34 
39 class LogStream {
40  std::string _prefix;
41  std::ostream* _log_stream;
42  bool _new_line;
43 
44 public:
49  LogStream(const std::string &prefix, std::ostream& log_stream)
50  : _prefix(prefix), _new_line(true) {
51  _log_stream = &log_stream;
52  }
53 
58  template<class T>
59  LogStream &operator<<(const T &arg) {
60  if (_new_line) {
61  (*_log_stream) << "[ " << _prefix << " ] ";
62  _new_line = false;
63  }
64 
65  (*_log_stream) << arg;
66  return *this;
67  }
68 
69  // Specializing for LogStreamEndLine to support slog::endl
70  LogStream& operator<< (const LogStreamEndLine &/*arg*/) {
71  _new_line = true;
72 
73  (*_log_stream) << std::endl;
74  return *this;
75  }
76 
77  // Specializing for LogStreamBoolAlpha to support slog::boolalpha
78  LogStream& operator<< (const LogStreamBoolAlpha &/*arg*/) {
79  (*_log_stream) << std::boolalpha;
80  return *this;
81  }
82 
83  // Specializing for std::vector and std::list
84  template<template<class, class> class Container, class T>
85  LogStream& operator<< (const Container<T, std::allocator<T>>& container) {
86  for (const auto& el : container) {
87  *this << el << slog::endl;
88  }
89  return *this;
90  }
91 };
92 
93 
94 static LogStream info("INFO", std::cout);
95 static LogStream debug("DEBUG", std::cout);
96 static LogStream warn("WARNING", std::cout);
97 static LogStream err("ERROR", std::cerr);
98 
99 } // namespace slog
The LogStreamBoolAlpha class implements bool printing for a log stream.
Definition: slog.hpp:30
The LogStreamEndLine class implements an end line marker for a log stream.
Definition: slog.hpp:21
The LogStream class implements a stream for sample logging.
Definition: slog.hpp:39
LogStream & operator<<(const T &arg)
A stream output operator to be used within the logger.
Definition: slog.hpp:59
LogStream(const std::string &prefix, std::ostream &log_stream)
A constructor. Creates a LogStream object.
Definition: slog.hpp:49