forked from OpenNMT/CTranslate2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.cc
84 lines (71 loc) · 2.2 KB
/
logging.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
74
75
76
77
78
79
80
81
82
83
84
#include "ctranslate2/logging.h"
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/spdlog.h>
#include "env.h"
namespace ctranslate2 {
static spdlog::level::level_enum to_spdlog_level(const LogLevel level) {
switch (level) {
case LogLevel::Off:
return spdlog::level::off;
case LogLevel::Critical:
return spdlog::level::critical;
case LogLevel::Error:
return spdlog::level::err;
case LogLevel::Warning:
return spdlog::level::warn;
case LogLevel::Info:
return spdlog::level::info;
case LogLevel::Debug:
return spdlog::level::debug;
case LogLevel::Trace:
return spdlog::level::trace;
default:
throw std::invalid_argument("Invalid log level");
}
}
static LogLevel to_ct2_level(const spdlog::level::level_enum level) {
switch (level) {
case spdlog::level::off:
return LogLevel::Off;
case spdlog::level::critical:
return LogLevel::Critical;
case spdlog::level::err:
return LogLevel::Error;
case spdlog::level::warn:
return LogLevel::Warning;
case spdlog::level::info:
return LogLevel::Info;
case spdlog::level::debug:
return LogLevel::Debug;
case spdlog::level::trace:
return LogLevel::Trace;
default:
throw std::invalid_argument("Invalid log level");
}
}
static LogLevel get_default_level() {
const auto level = read_int_from_env("CT2_VERBOSE", 0);
if (level < -3 || level > 3)
throw std::invalid_argument("Invalid log level " + std::to_string(level)
+ " (should be between -3 and 3)");
return static_cast<LogLevel>(level);
}
static void init_logger() {
auto logger = spdlog::stderr_logger_mt("ctranslate2");
logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%n] [thread %t] [%l] %v");
spdlog::set_default_logger(logger);
set_log_level(get_default_level());
}
// Initialize the global logger on program start.
static struct LoggerInit {
LoggerInit() {
init_logger();
}
} logger_init;
void set_log_level(const LogLevel level) {
spdlog::set_level(to_spdlog_level(level));
}
LogLevel get_log_level() {
return to_ct2_level(spdlog::get_level());
}
}