1 // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 
6 #pragma once
7 
8 #include <ctime>
9 #include "memory/arena.h"
10 #include "port/sys_time.h"
11 #include "rocksdb/env.h"
12 #include "util/autovector.h"
13 
14 namespace ROCKSDB_NAMESPACE {
15 
16 class Logger;
17 
18 // A class to buffer info log entries and flush them in the end.
19 class LogBuffer {
20  public:
21   // log_level: the log level for all the logs
22   // info_log:  logger to write the logs to
23   LogBuffer(const InfoLogLevel log_level, Logger* info_log);
24 
25   // Add a log entry to the buffer. Use default max_log_size.
26   // max_log_size indicates maximize log size, including some metadata.
27   void AddLogToBuffer(size_t max_log_size, const char* format, va_list ap);
28 
IsEmpty()29   size_t IsEmpty() const { return logs_.empty(); }
30 
31   // Flush all buffered log to the info log.
32   void FlushBufferToLog();
33   static const size_t kDefaultMaxLogSize = 512;
34 
35  private:
36   // One log entry with its timestamp
37   struct BufferedLog {
38     struct timeval now_tv;  // Timestamp of the log
39     char message[1];        // Beginning of log message
40   };
41 
42   const InfoLogLevel log_level_;
43   Logger* info_log_;
44   Arena arena_;
45   autovector<BufferedLog*> logs_;
46 };
47 
48 // Add log to the LogBuffer for a delayed info logging. It can be used when
49 // we want to add some logs inside a mutex.
50 // max_log_size indicates maximize log size, including some metadata.
51 extern void LogToBuffer(LogBuffer* log_buffer, size_t max_log_size,
52                         const char* format, ...);
53 // Same as previous function, but with default max log size.
54 extern void LogToBuffer(LogBuffer* log_buffer, const char* format, ...);
55 
56 }  // namespace ROCKSDB_NAMESPACE
57