log.h 10.8 KB
Newer Older
羽飞's avatar
羽飞 已提交
1
/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
羽飞's avatar
羽飞 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Longda on 2010
//

15
#pragma once
羽飞's avatar
羽飞 已提交
16

17
#include <sys/time.h>
羽飞's avatar
羽飞 已提交
18 19 20 21 22 23 24 25 26 27
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>

#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <string>
28
#include  <functional>
羽飞's avatar
羽飞 已提交
29 30 31 32 33

#include "common/defs.h"

namespace common {

羽飞's avatar
羽飞 已提交
34 35 36 37 38
const unsigned int ONE_KILO = 1024;
const unsigned int ONE_MILLION = ONE_KILO * ONE_KILO;
const unsigned int ONE_GIGA = ONE_MILLION * ONE_KILO;
const unsigned int FILENAME_LENGTH_MAX = 256;  // the max filename length

羽飞's avatar
羽飞 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52
const int LOG_STATUS_OK = 0;
const int LOG_STATUS_ERR = 1;
const int LOG_MAX_LINE = 100000;

typedef enum {
  LOG_LEVEL_PANIC = 0,
  LOG_LEVEL_ERR = 1,
  LOG_LEVEL_WARN = 2,
  LOG_LEVEL_INFO = 3,
  LOG_LEVEL_DEBUG = 4,
  LOG_LEVEL_TRACE = 5,
  LOG_LEVEL_LAST
} LOG_LEVEL;

53
typedef enum { LOG_ROTATE_BYDAY = 0, LOG_ROTATE_BYSIZE, LOG_ROTATE_LAST } LOG_ROTATE;
羽飞's avatar
羽飞 已提交
54

55 56
class Log 
{
57
public:
羽飞's avatar
羽飞 已提交
58 59 60 61 62 63 64 65 66 67 68 69
  Log(const std::string &log_name, const LOG_LEVEL log_level = LOG_LEVEL_INFO,
      const LOG_LEVEL console_level = LOG_LEVEL_WARN);
  ~Log(void);

  static int init(const std::string &log_file);

  /**
   * These functions won't output header information such as __FUNCTION__,
   * The user should control these information
   * If the header information should be outputed
   * please use LOG_PANIC, LOG_ERROR ...
   */
70
  template <class T>
羽飞's avatar
羽飞 已提交
71 72
  Log &operator<<(T message);

73
  template <class T>
羽飞's avatar
羽飞 已提交
74 75
  int panic(T message);

76
  template <class T>
羽飞's avatar
羽飞 已提交
77 78
  int error(T message);

79
  template <class T>
羽飞's avatar
羽飞 已提交
80 81
  int warnning(T message);

82
  template <class T>
羽飞's avatar
羽飞 已提交
83 84
  int info(T message);

85
  template <class T>
羽飞's avatar
羽飞 已提交
86 87
  int debug(T message);

88
  template <class T>
羽飞's avatar
羽飞 已提交
89 90
  int trace(T message);

91
  int output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...);
羽飞's avatar
羽飞 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

  int set_console_level(const LOG_LEVEL console_level);
  LOG_LEVEL get_console_level();

  int set_log_level(const LOG_LEVEL log_level);
  LOG_LEVEL get_log_level();

  int set_rotate_type(LOG_ROTATE rotate_type);
  LOG_ROTATE get_rotate_type();

  const char *prefix_msg(const LOG_LEVEL level);

  /**
   * Set Default Module list
   * if one module is default module,
   * it will output whatever output level is lower than log_level_ or not
   */
  void set_default_module(const std::string &modules);
  bool check_output(const LOG_LEVEL log_level, const char *module);

  int rotate(const int year = 0, const int month = 0, const int day = 0);

114 115 116
  void set_context_getter(std::function<intptr_t()> context_getter);
  intptr_t context_id();
  
117
private:
羽飞's avatar
羽飞 已提交
118 119 120 121 122 123
  void check_param_valid();

  int rotate_by_size();
  int rename_old_logs();
  int rotate_by_day(const int year, const int month, const int day);

124
  template <class T>
羽飞's avatar
羽飞 已提交
125 126
  int out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &message);

127
private:
羽飞's avatar
羽飞 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  pthread_mutex_t lock_;
  std::ofstream ofs_;
  std::string log_name_;
  LOG_LEVEL log_level_;
  LOG_LEVEL console_level_;

  typedef struct _LogDate {
    int year_;
    int mon_;
    int day_;
  } LogDate;
  LogDate log_date_;
  int log_line_;
  int log_max_line_;
  LOG_ROTATE rotate_type_;

  typedef std::map<LOG_LEVEL, std::string> LogPrefixMap;
  LogPrefixMap prefix_map_;

  typedef std::set<std::string> DefaultSet;
  DefaultSet default_set_;
149 150

  std::function<intptr_t()> context_getter_;
羽飞's avatar
羽飞 已提交
151 152 153
};

class LoggerFactory {
154
public:
羽飞's avatar
羽飞 已提交
155 156 157
  LoggerFactory();
  virtual ~LoggerFactory();

158 159
  static int init(const std::string &log_file, Log **logger, LOG_LEVEL log_level = LOG_LEVEL_INFO,
      LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
羽飞's avatar
羽飞 已提交
160

161 162
  static int init_default(const std::string &log_file, LOG_LEVEL log_level = LOG_LEVEL_INFO,
      LOG_LEVEL console_level = LOG_LEVEL_WARN, LOG_ROTATE rotate_type = LOG_ROTATE_BYDAY);
羽飞's avatar
羽飞 已提交
163 164 165 166
};

extern Log *g_log;

L
Longda 已提交
167
#ifndef __FILE_NAME__
168
#define __FILE_NAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
L
Longda 已提交
169 170
#endif

171
#define LOG_HEAD_SIZE 128
172

173 174
#define LOG_HEAD(prefix, level)                                            \
  if (common::g_log) {                                                     \
175 176 177
    struct timeval tv;                                                     \
    gettimeofday(&tv, NULL);                                               \
    struct tm *p = localtime(&tv.tv_sec);                                  \
178
    char sz_head[LOG_HEAD_SIZE] = {0};                                     \
179
    if (p) {                                                               \
180
      int usec = (int)tv.tv_usec;                                          \
181
      snprintf(sz_head, LOG_HEAD_SIZE,                                     \
182
          "%04d-%02d-%02d %02d:%02d:%02u.%06d pid:%u tid:%llx ctx:%lx",    \
183 184 185 186 187 188
          p->tm_year + 1900,                                               \
          p->tm_mon + 1,                                                   \
          p->tm_mday,                                                      \
          p->tm_hour,                                                      \
          p->tm_min,                                                       \
          p->tm_sec,                                                       \
189
          usec,                                                            \
羽飞's avatar
羽飞 已提交
190
          (int32_t)getpid(),                                               \
191 192
          gettid(),                                                        \
          common::g_log->context_id());                                    \
193 194 195 196
      common::g_log->rotate(p->tm_year + 1900, p->tm_mon + 1, p->tm_mday); \
    }                                                                      \
    snprintf(prefix,                                                       \
        sizeof(prefix),                                                    \
197
        "[%s %s %s@%s:%u] >> ",                                            \
198 199
        sz_head,                                                           \
        (common::g_log)->prefix_msg(level),                                \
200
        __FUNCTION__,                                                      \
201
        __FILE_NAME__,                                                     \
羽飞's avatar
羽飞 已提交
202
        (int32_t)__LINE__                                                  \
203
        );                                                                 \
羽飞's avatar
羽飞 已提交
204 205
  }

206 207 208 209 210 211 212 213
#define LOG_OUTPUT(level, fmt, ...)                                    \
  do {                                                                 \
    using namespace common;                                            \
    if (g_log && g_log->check_output(level, __FILE_NAME__)) {          \
      char prefix[ONE_KILO] = {0};                                     \
      LOG_HEAD(prefix, level);                                         \
      g_log->output(level, __FILE_NAME__, prefix, fmt, ##__VA_ARGS__); \
    }                                                                  \
羽飞's avatar
羽飞 已提交
214 215
  } while (0)

216
#define LOG_DEFAULT(fmt, ...) LOG_OUTPUT(common::g_log->get_log_level(), fmt, ##__VA_ARGS__)
羽飞's avatar
羽飞 已提交
217 218 219 220 221 222 223
#define LOG_PANIC(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_PANIC, fmt, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_ERR, fmt, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_WARN, fmt, ##__VA_ARGS__)
#define LOG_INFO(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_INFO, fmt, ##__VA_ARGS__)
#define LOG_DEBUG(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__)
#define LOG_TRACE(fmt, ...) LOG_OUTPUT(common::LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__)

224 225 226
template <class T>
Log &Log::operator<<(T msg)
{
羽飞's avatar
羽飞 已提交
227 228 229 230 231
  // at this time, the input level is the default log level
  out(console_level_, log_level_, msg);
  return *this;
}

232 233 234
template <class T>
int Log::panic(T message)
{
羽飞's avatar
羽飞 已提交
235 236 237
  return out(LOG_LEVEL_PANIC, LOG_LEVEL_PANIC, message);
}

238 239 240
template <class T>
int Log::error(T message)
{
羽飞's avatar
羽飞 已提交
241 242 243
  return out(LOG_LEVEL_ERR, LOG_LEVEL_ERR, message);
}

244 245 246
template <class T>
int Log::warnning(T message)
{
羽飞's avatar
羽飞 已提交
247 248 249
  return out(LOG_LEVEL_WARN, LOG_LEVEL_WARN, message);
}

250 251 252
template <class T>
int Log::info(T message)
{
羽飞's avatar
羽飞 已提交
253 254 255
  return out(LOG_LEVEL_INFO, LOG_LEVEL_INFO, message);
}

256 257 258
template <class T>
int Log::debug(T message)
{
羽飞's avatar
羽飞 已提交
259 260 261
  return out(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, message);
}

262 263 264
template <class T>
int Log::trace(T message)
{
羽飞's avatar
羽飞 已提交
265 266 267
  return out(LOG_LEVEL_TRACE, LOG_LEVEL_TRACE, message);
}

268 269 270
template <class T>
int Log::out(const LOG_LEVEL console_level, const LOG_LEVEL log_level, T &msg)
{
羽飞's avatar
羽飞 已提交
271
  bool locked = false;
272 273
  if (console_level < LOG_LEVEL_PANIC || console_level > console_level_ || log_level < LOG_LEVEL_PANIC ||
      log_level > log_level_) {
羽飞's avatar
羽飞 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    return LOG_STATUS_OK;
  }
  try {
    char prefix[ONE_KILO] = {0};
    LOG_HEAD(prefix, log_level);
    if (LOG_LEVEL_PANIC <= console_level && console_level <= console_level_) {
      std::cout << prefix_map_[console_level] << msg;
    }

    if (LOG_LEVEL_PANIC <= log_level && log_level <= log_level_) {
      pthread_mutex_lock(&lock_);
      locked = true;
      ofs_ << prefix;
      ofs_ << msg;
      ofs_.flush();
      log_line_++;
      pthread_mutex_unlock(&lock_);
      locked = false;
    }
  } catch (std::exception &e) {
    if (locked) {
      pthread_mutex_unlock(&lock_);
    }
    std::cerr << e.what() << std::endl;
    return LOG_STATUS_ERR;
  }

  return LOG_STATUS_OK;
}

#ifndef ASSERT
305
#ifdef DEBUG
306 307 308
#define ASSERT(expression, description, ...)   \
  do {                                         \
    if (!(expression)) {                       \
羽飞's avatar
羽飞 已提交
309
      LOG_PANIC(description, ##__VA_ARGS__);   \
310 311
      assert(expression);                      \
    }                                          \
羽飞's avatar
羽飞 已提交
312
  } while (0)
313 314

#else // DEBUG
羽飞's avatar
羽飞 已提交
315 316
#define ASSERT(expression, description, ...)   \
  do {                                         \
317
     (void)(expression);                       \
羽飞's avatar
羽飞 已提交
318
  } while (0)
319 320
#endif // DEBUG

321
#endif  // ASSERT
羽飞's avatar
羽飞 已提交
322

323
#define SYS_OUTPUT_FILE_POS ", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__
羽飞's avatar
羽飞 已提交
324 325
#define SYS_OUTPUT_ERROR ",error:" << errno << ":" << strerror(errno)

326 327 328 329 330
/**
 * 获取当前函数调用栈
 */
const char *lbt();

331 332 333 334 335 336
/**
 * @brief 设置一个在日志中打印当前上下文信息的回调函数
 * @details 比如设置一个获取当前session标识的函数,那么每次在打印日志时都会输出session信息。
 *          这个回调函数返回了一个intptr_t类型的数据,可能返回字符串更好,但是现在够用了。
 */
void set_log_context_getter(std::function<intptr_t()> context_getter);
337

338 339 340
extern std::function<intptr_t()> g_context_getter;

}  // namespace common