-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.cpp
More file actions
104 lines (99 loc) · 2.65 KB
/
log.cpp
File metadata and controls
104 lines (99 loc) · 2.65 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <cstdlib>
#include <string>
#include <vector>
#include <memory>
#include "log.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
static void init_default_log(const std::string& filename);
static void set_log_level();
static uint32_t get_log_file_size();
static uint32_t get_log_file_count();
void init_log(const std::string& filename)
{
init_default_log(filename);
set_log_level();
}
void set_level(const std::string& level)
{
spdlog::set_level(spdlog::level::info);
if (level == "debug")
{
spdlog::set_level(spdlog::level::debug);
}
else if (level == "warn" || level == "warning")
{
spdlog::set_level(spdlog::level::warn);
}
else if (level == "err" || level == "error")
{
spdlog::set_level(spdlog::level::err);
}
else if (level == "trace")
{
spdlog::set_level(spdlog::level::trace);
}
}
void shutdown_log()
{
spdlog::default_logger()->flush();
spdlog::shutdown();
}
static void init_default_log(const std::string& filename)
{
uint32_t file_size = get_log_file_size();
uint32_t file_count = get_log_file_count();
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
std::string file_sink_error;
try
{
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>(filename, file_size, file_count));
}
catch (const spdlog::spdlog_ex& ex)
{
file_sink_error = ex.what();
}
auto logger = std::make_shared<spdlog::logger>("", begin(sinks), end(sinks));
spdlog::set_default_logger(logger);
spdlog::flush_every(std::chrono::seconds(3));
spdlog::set_level(spdlog::level::info);
spdlog::set_pattern("%Y%m%d %T.%f %t %L %v %s:%#");
if (!file_sink_error.empty())
{
spdlog::warn("failed to initialize file log sink: {}", file_sink_error);
}
}
static void set_log_level()
{
spdlog::set_level(spdlog::level::info);
if (getenv("TRACE") != nullptr)
{
spdlog::set_level(spdlog::level::trace);
}
else if (getenv("DEBUG") != nullptr)
{
spdlog::set_level(spdlog::level::debug);
}
}
static uint32_t get_log_file_size()
{
constexpr auto kFileSize = 50 * 1024 * 1024;
char* file_size = getenv("LOG_FILE_SIZE");
if (file_size != nullptr)
{
return atoi(file_size);
}
return kFileSize;
}
static uint32_t get_log_file_count()
{
constexpr auto kFileCount = 5;
char* file_count = getenv("LOG_FILE_COUNT");
if (file_count != nullptr)
{
return atoi(file_count);
}
return kFileCount;
}