SimpleLog.h 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// 简易日志

#ifndef __SIMPLE_LOG_H__
#define __SIMPLE_LOG_H__

#include <time.h>
#include <string>
#include <map>
#include <thread>
#include <mutex>
liucong's avatar
liucong committed
11
#if(defined WIN32 || defined _WIN32)
12
13
14
15
16
17
18
19
#include <Windows.h>
#else
#include <sys/time.h>
#endif

using namespace std;

/** 简易日志
liucong's avatar
liucong committed
20
 *
liucong's avatar
liucong committed
21
 * 不依赖于其他第三方库,只需要包含一个头文件就可以使用。提供了4种日志级别,包括INFO,DEBUG,WARN和ERROR。
liucong's avatar
liucong committed
22
 *
23
 * 示例1:
liucong's avatar
liucong committed
24
25
    //
 初始化日志,在./Log/目录下创建两个日志文件log1.log和log2.log(注意:目录./Log/需要存在,否则日志创建失败)
26
27
28
29
30
31
32
33
34
35
36
    LogManager::GetInstance()->Initialize("./Log/","log1");
    LogManager::GetInstance()->Initialize("./Log/","log2");

    // 写日志
    string log = "Hello World";
    LOG_INFO(LogManager::GetInstance()->GetLogFile("log1"), "%s\n", log.c_str()); // 写入log1.log
    LOG_INFO(LogManager::GetInstance()->GetLogFile("log2"), "%s\n", log.c_str()); // 写入log2.log

    // 关闭日志
    LogManager::GetInstance()->Close("log1");
    LogManager::GetInstance()->Close("log2");
liucong's avatar
liucong committed
37

38
39
40
  * 示例2:
    // 将日志输出到控制台
    string log = "Hello World";
liucong's avatar
liucong committed
41
    LOG_INFO(stdout, "%s\n", log.c_str());
42
43
44
45
46
47
48
49
50
51
52

  * 注意:
    1. 需要C++11
    2. 多线程的时候需要加锁(打开#define LOG_MUTEX),否则会导致日志显示混乱

*/

// #define LOG_MUTEX  // 加锁

class LogManager
{
liucong's avatar
liucong committed
53
54
    private:
    LogManager() {}
55

liucong's avatar
liucong committed
56
57
58
    public:
    ~LogManager() {}
    inline void Initialize(const string& parentPath, const string& logName)
59
60
    {
        // 日志名为空表示输出到控制台
liucong's avatar
liucong committed
61
        if(logName.size() == 0)
62
63
64
65
            return;

        // 查找该日志文件,如果没有则创建
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
liucong's avatar
liucong committed
66
        if(iter == logMap.end())
67
        {
liucong's avatar
liucong committed
68
69
70
            string pathOfLog = parentPath + logName + ".log";
            FILE* logFile    = fopen(pathOfLog.c_str(), "a"); // w:覆盖原有文件,a:追加
            if(logFile != NULL)
71
72
73
74
75
            {
                logMap.insert(std::make_pair(logName, logFile));
            }
        }
    }
liucong's avatar
liucong committed
76
    inline FILE* GetLogFile(const string& logName)
77
    {
liucong's avatar
liucong committed
78
79
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
        if(iter == logMap.end())
80
81
82
83
84
85
        {
            return NULL;
        }

        return (*iter).second;
    }
liucong's avatar
liucong committed
86
    inline void Close(const string& logName)
87
    {
liucong's avatar
liucong committed
88
89
        std::map<string, FILE*>::const_iterator iter = logMap.find(logName);
        if(iter == logMap.end())
90
91
92
93
94
95
96
        {
            return;
        }

        fclose((*iter).second);
        logMap.erase(iter);
    }
liucong's avatar
liucong committed
97
    inline std::mutex& GetLogMutex() { return logMutex; }
98
99
100
101
102
103
104

    // Singleton
    static LogManager* GetInstance()
    {
        static LogManager logManager;
        return &logManager;
    }
liucong's avatar
liucong committed
105
106

    private:
107
108
109
110
111
    std::map<string, FILE*> logMap;
    std::mutex logMutex;
};

#ifdef LOG_MUTEX
liucong's avatar
liucong committed
112
113
#define LOCK LogManager::GetInstance()->GetLogMutex().lock()
#define UNLOCK LogManager::GetInstance()->GetLogMutex().unlock()
114
#else
liucong's avatar
liucong committed
115
116
#define LOCK
#define UNLOCK
117
118
119
#endif

// log time
liucong's avatar
liucong committed
120
typedef struct _LogTime
121
122
123
124
125
126
127
128
129
130
{
    string year;
    string month;
    string day;
    string hour;
    string minute;
    string second;
    string millisecond; // ms
    string microsecond; // us
    string weekDay;
liucong's avatar
liucong committed
131
} LogTime;
132
133
134
135
136

inline LogTime GetTime()
{
    LogTime currentTime;

liucong's avatar
liucong committed
137
#if(defined WIN32 || defined _WIN32)
138
139
140
    SYSTEMTIME systemTime;
    GetLocalTime(&systemTime);

liucong's avatar
liucong committed
141
    char temp[8] = {0};
142
    sprintf(temp, "%04d", systemTime.wYear);
liucong's avatar
liucong committed
143
    currentTime.year = string(temp);
144
    sprintf(temp, "%02d", systemTime.wMonth);
liucong's avatar
liucong committed
145
    currentTime.month = string(temp);
146
    sprintf(temp, "%02d", systemTime.wDay);
liucong's avatar
liucong committed
147
    currentTime.day = string(temp);
148
    sprintf(temp, "%02d", systemTime.wHour);
liucong's avatar
liucong committed
149
    currentTime.hour = string(temp);
150
    sprintf(temp, "%02d", systemTime.wMinute);
liucong's avatar
liucong committed
151
    currentTime.minute = string(temp);
152
    sprintf(temp, "%02d", systemTime.wSecond);
liucong's avatar
liucong committed
153
    currentTime.second = string(temp);
154
    sprintf(temp, "%03d", systemTime.wMilliseconds);
liucong's avatar
liucong committed
155
    currentTime.millisecond = string(temp);
156
    sprintf(temp, "%d", systemTime.wDayOfWeek);
liucong's avatar
liucong committed
157
    currentTime.weekDay = string(temp);
158
#else
liucong's avatar
liucong committed
159
160
    struct timeval tv;
    struct tm* p;
161
162
163
    gettimeofday(&tv, NULL);
    p = localtime(&tv.tv_sec);

liucong's avatar
liucong committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    char temp[8] = {0};
    sprintf(temp, "%04d", 1900 + p->tm_year);
    currentTime.year = string(temp);
    sprintf(temp, "%02d", 1 + p->tm_mon);
    currentTime.month = string(temp);
    sprintf(temp, "%02d", p->tm_mday);
    currentTime.day = string(temp);
    sprintf(temp, "%02d", p->tm_hour);
    currentTime.hour = string(temp);
    sprintf(temp, "%02d", p->tm_min);
    currentTime.minute = string(temp);
    sprintf(temp, "%02d", p->tm_sec);
    currentTime.second = string(temp);
    sprintf(temp, "%03d", (int)(tv.tv_usec / 1000));
178
179
180
181
182
183
184
185
186
    currentTime.millisecond = string(temp);
    sprintf(temp, "%03d", (int)(tv.tv_usec % 1000));
    currentTime.microsecond = string(temp);
    sprintf(temp, "%d", p->tm_wday);
    currentTime.weekDay = string(temp);
#endif
    return currentTime;
}

liucong's avatar
liucong committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#define LOG_TIME(logFile)                               \
    do                                                  \
    {                                                   \
        LogTime currentTime = GetTime();                \
        fprintf(((logFile == NULL) ? stdout : logFile), \
                "%s-%s-%s %s:%s:%s.%s\t",               \
                currentTime.year.c_str(),               \
                currentTime.month.c_str(),              \
                currentTime.day.c_str(),                \
                currentTime.hour.c_str(),               \
                currentTime.minute.c_str(),             \
                currentTime.second.c_str(),             \
                currentTime.millisecond.c_str());       \
    } while(0)
201

liucong's avatar
liucong committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#define LOG_INFO(logFile, logInfo, ...)                                          \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "INFO\t");               \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#define LOG_DEBUG(logFile, logInfo, ...)                                         \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "DEBUG\t");              \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)
233

liucong's avatar
liucong committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#define LOG_ERROR(logFile, logInfo, ...)                                         \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "ERROR\t");              \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#define LOG_WARN(logFile, logInfo, ...)                                          \
    do                                                                           \
    {                                                                            \
        LOCK;                                                                    \
        LOG_TIME(logFile);                                                       \
        fprintf(((logFile == NULL) ? stdout : logFile), "WARN\t");               \
        fprintf(((logFile == NULL) ? stdout : logFile),                          \
                "[%s:%d (%s) ]: ",                                               \
                __FILE__,                                                        \
                __LINE__,                                                        \
                __FUNCTION__);                                                   \
        fprintf(((logFile == NULL) ? stdout : logFile), logInfo, ##__VA_ARGS__); \
        fflush(logFile);                                                         \
        UNLOCK;                                                                  \
    } while(0)

#endif // __SIMPLE_LOG_H__