-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.cc
73 lines (56 loc) · 1.34 KB
/
log.cc
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
#include "log.h"
#include <iostream>
#include <fstream>
#include <string>
#include <random>
#include <deque>
static const int MAX_LOG_COUNT = 1024;
static std::deque<std::string> logs;
static bool is_log_enabled = true;
void EnableLog(bool enable)
{
is_log_enabled = enable;
}
void AddLog(const char *str, ...)
{
if (!is_log_enabled)
return;
// Format
static char buf[1024] = {'\0'};
va_list va;
va_start(va, str);
vsprintf(buf, str, va);
va_end(va);
// Push
logs.push_back(buf);
if (logs.size() > MAX_LOG_COUNT)
logs.pop_front();
}
void SaveLog()
{
if (!is_log_enabled)
return;
// Random file name
std::random_device rd;
std::mt19937 rng(rd());
const std::string filename = "log_tetris_" + std::to_string(rng()) + ".txt";
// Save
std::ofstream ofs(filename);
if (!ofs) {
std::cerr << "can't open file: " << filename << std::endl;
return;
}
for (auto log: logs)
ofs << log << std::endl;
}
void Assert(int expr, const char *str, const char *file, int line)
{
if (expr)
return;
fprintf(stderr, "Assertion failed: '%s'\n", str);
fprintf(stderr, "File: %s, Line: %d\n", file, line);
AddLog("Assertion failed: '%s'", str);
AddLog("File: %s, Line: %d", file, line);
SaveLog();
std::abort();
}