wangzhengquan
2021-01-20 a4d18d6ab3216ce1bf8052f0fdc4ea34bc6385e8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#ifndef __LOGGER_H__
#define __LOGGER_H__
 
#include "usg_common.h"
#include "usg_typedef.h"
 
struct LoggerConfig {
  std::string logFile;
  int level; 
  bool console;
};
 
class Logger {
private:
  std::string configFile;
  LoggerConfig config;
  FILE *logFile;
 
  void dolog(const char *fmt, va_list ap, int level, int err = 0) {
    char buf[MAXLINE];
 
    struct timeval tv;
    struct tm *info;
    gettimeofday(&tv, NULL);
    info = localtime(&tv.tv_sec);
    strftime(buf, MAXBUF - 1, "%Y-%d-%m %H:%M:%S", info);
    snprintf(buf + strlen(buf), MAXBUF - strlen(buf) - 1, ",%ld [%s] ",  tv.tv_usec, strlevel(level));
    vsnprintf(buf + strlen(buf), MAXBUF - strlen(buf) - 1, fmt, ap);
 
    if (err != 0) {
      snprintf(buf + strlen(buf), MAXBUF - strlen(buf) - 1, ": %s", strerror(err));
    }
    strcat(buf, "\n");
    fflush(stdout); /* in case stdout and stderr are the same */
    
    if(logFile != NULL) {
      fputs(buf, logFile);
    }
    if(config.console) {
       fputs(buf, stdout);
    }
   
    fflush(NULL); /* flushes all stdio output streams */
  }
 
  
  void init();
 
private:
  static const char *LOGGER_LEVEL_STR[] ;
public:
  enum LoggerLevel { ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF };
 
 
  Logger(int l = INFO);
  Logger(std::string cf);
  Logger(LoggerConfig & conf);
 
  ~Logger();
 
  void log(int _level, const char *fmt, ...);
 
  void debug(const char *fmt, ...);
  void info(const char *fmt, ...);
  void warn(const char *fmt, ...);
  void error(const char *fmt, ...);
  void error(int err, const char *fmt, ...);
  void fatal(const char *fmt, ...);
  void fatal(int err, const char *fmt, ...) ;
 
  static const char * strlevel(int level);
};
 
#endif