blob: 4443f7cdfe01b77926086a6f47dc5e54128a73a0 [file] [log] [blame]
Ian Hodson2ee91b42012-05-14 12:29:36 +01001// Copyright 2009 The RE2 Authors. All Rights Reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Simplified version of Google's logging.
6
7#ifndef RE2_UTIL_LOGGING_H__
8#define RE2_UTIL_LOGGING_H__
9
10#include <unistd.h> /* for write */
11#include <sstream>
12
13// Debug-only checking.
14#define DCHECK(condition) assert(condition)
15#define DCHECK_EQ(val1, val2) assert((val1) == (val2))
16#define DCHECK_NE(val1, val2) assert((val1) != (val2))
17#define DCHECK_LE(val1, val2) assert((val1) <= (val2))
18#define DCHECK_LT(val1, val2) assert((val1) < (val2))
19#define DCHECK_GE(val1, val2) assert((val1) >= (val2))
20#define DCHECK_GT(val1, val2) assert((val1) > (val2))
21
22// Always-on checking
23#define CHECK(x) if(x){}else LogMessageFatal(__FILE__, __LINE__).stream() << "Check failed: " #x
24#define CHECK_LT(x, y) CHECK((x) < (y))
25#define CHECK_GT(x, y) CHECK((x) > (y))
26#define CHECK_LE(x, y) CHECK((x) <= (y))
27#define CHECK_GE(x, y) CHECK((x) >= (y))
28#define CHECK_EQ(x, y) CHECK((x) == (y))
29#define CHECK_NE(x, y) CHECK((x) != (y))
30
31#define LOG_INFO LogMessage(__FILE__, __LINE__)
32#define LOG_ERROR LOG_INFO
33#define LOG_WARNING LOG_INFO
34#define LOG_FATAL LogMessageFatal(__FILE__, __LINE__)
35#define LOG_QFATAL LOG_FATAL
36
37#define VLOG(x) if((x)>0){}else LOG_INFO.stream()
38
39#ifdef NDEBUG
40#define DEBUG_MODE 0
41#define LOG_DFATAL LOG_ERROR
42#else
43#define DEBUG_MODE 1
44#define LOG_DFATAL LOG_FATAL
45#endif
46
47#define LOG(severity) LOG_ ## severity.stream()
48
49class LogMessage {
50 public:
Alexander Gutkin0d4c5232013-02-28 13:47:27 +000051 LogMessage(const char* file, int line) : flushed_(false) {
Ian Hodson2ee91b42012-05-14 12:29:36 +010052 stream() << file << ":" << line << ": ";
53 }
Alexander Gutkin0d4c5232013-02-28 13:47:27 +000054 void Flush() {
Ian Hodson2ee91b42012-05-14 12:29:36 +010055 stream() << "\n";
56 string s = str_.str();
Alexander Gutkin0d4c5232013-02-28 13:47:27 +000057 int n = (int)s.size(); // shut up msvc
58 if(write(2, s.data(), n) < 0) {} // shut up gcc
59 flushed_ = true;
60 }
61 ~LogMessage() {
62 if (!flushed_) {
63 Flush();
64 }
Ian Hodson2ee91b42012-05-14 12:29:36 +010065 }
66 ostream& stream() { return str_; }
67
68 private:
Alexander Gutkin0d4c5232013-02-28 13:47:27 +000069 bool flushed_;
Ian Hodson2ee91b42012-05-14 12:29:36 +010070 std::ostringstream str_;
71 DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
72};
73
74class LogMessageFatal : public LogMessage {
75 public:
76 LogMessageFatal(const char* file, int line)
77 : LogMessage(file, line) { }
78 ~LogMessageFatal() {
Alexander Gutkin0d4c5232013-02-28 13:47:27 +000079 Flush();
Ian Hodson2ee91b42012-05-14 12:29:36 +010080 abort();
81 }
82 private:
83 DISALLOW_EVIL_CONSTRUCTORS(LogMessageFatal);
84};
85
86#endif // RE2_UTIL_LOGGING_H__