btllib

status.hpp
1 #ifndef BTLLIB_STATUS_HPP
2 #define BTLLIB_STATUS_HPP
3
4 #include <cstdlib>
5 #include <cstring>
6 #include <ctime>
7 #include <iostream>
8 #include <string>
9
10 namespace btllib {
11
12 inline std::string
13 get_time();
14 inline void
15 log_info(const std::string& msg);
16 inline void
17 log_warning(const std::string& msg);
18 inline void
19 log_error(const std::string& msg);
20 inline void
21 check_error(bool condition, const std::string& msg);
22 inline void
23 check_warning(bool condition, const std::string& msg);
24 inline void
25 check_stream(const std::ios& stream, const std::string& name);
26
27 inline std::string
28 get_time()
29 {
30 time_t now;
31 time(&now);
32 char buf[sizeof("2011-10-08T07:07:09Z")];
33 strftime(buf, sizeof buf, "%F %T", localtime(&now));
34 return std::string(buf);
35 }
36
37 inline void
38 log_info(const std::string& msg)
39 {
40 std::cerr << '[' << get_time() << "] [INFO] " << msg << std::endl;
41 }
42
43 inline void
44 log_warning(const std::string& msg)
45 {
46 std::cerr << '[' << get_time() << "] [WARNING] " << msg << std::endl;
47 }
48
49 inline void
50 log_error(const std::string& msg)
51 {
52 std::cerr << '[' << get_time() << "] [ERROR] " << msg << std::endl;
53 }
54
55 inline void
56 check_error(bool condition, const std::string& msg)
57 {
58 if (condition) {
59 log_error(msg);
60 std::exit(EXIT_FAILURE);
61 }
62 }
63
64 inline void
65 check_warning(bool condition, const std::string& msg)
66 {
67 if (condition) {
68 log_warning(msg);
69 }
70 }
71
72 inline void
73 check_stream(const std::ios& stream, const std::string& name)
74 {
75 check_error(!stream.good(),
76 "'" + name + "' stream error: " + std::strerror(errno));
77 }
78
79 } // namespace btllib
80
81 #endif