-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.h
50 lines (41 loc) · 1.15 KB
/
logger.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (c) 2017 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#ifndef LOGGER_H
#define LOGGER_H
#include <iomanip>
#include <mutex>
#include <ostream>
#include <streambuf>
#include <thread>
// Log entry that is in the process of being written. This class
// serializes output to the stream and also ensures all entries have a
// trailing newline.
class LogTransaction : public std::ostream {
public:
LogTransaction(std::streambuf* streambuf, std::mutex* streambuf_lock)
: std::ostream(streambuf), ostream_guard_(*streambuf_lock) {
}
~LogTransaction() {
*this << std::endl;
}
private:
std::lock_guard<std::mutex> ostream_guard_;
};
// Wrapper around std::ostream for writing log entries.
//
// C++ streams are not required to be thread-safe. This class protects
// an output stream with a mutex.
class Logger {
public:
explicit Logger(std::streambuf* streambuf) : streambuf_(streambuf) {
}
// TODO(ed): Should we add support for logging severities?
LogTransaction Log() {
return LogTransaction(streambuf_, &streambuf_lock_);
}
private:
std::mutex streambuf_lock_;
std::streambuf* streambuf_;
};
#endif