1// 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:
51  LogMessage(const char* file, int line) : flushed_(false) {
52    stream() << file << ":" << line << ": ";
53  }
54  void Flush() {
55    stream() << "\n";
56    string s = str_.str();
57    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    }
65  }
66  ostream& stream() { return str_; }
67
68 private:
69  bool flushed_;
70  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() {
79    Flush();
80    abort();
81  }
82 private:
83  DISALLOW_EVIL_CONSTRUCTORS(LogMessageFatal);
84};
85
86#endif  // RE2_UTIL_LOGGING_H__
87