-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathlogger.rs
More file actions
171 lines (144 loc) · 5.12 KB
/
Copy pathlogger.rs
File metadata and controls
171 lines (144 loc) · 5.12 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::sync::LazyLock;
use console::style;
use log::{Level, LevelFilter, Log};
use regex::Regex;
use simplelog::SharedLogger;
use std::{
env,
io::Write,
sync::Mutex,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{
logger::{GroupEvent, get_announcement_event, get_group_event, get_json_event},
run_environment::logger::should_provider_logger_handle_record,
};
static GITLAB_SECTION_ID_SANITIZE_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"[^\d\w\-_]").expect("Failed to compile GitLab SectionId regex"));
/// Unicode Escape character
///
/// https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#general-ascii-codes
const U_ESC: char = '\x1B';
/// Unicode Carriage Return character
///
/// https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#general-ascii-codes
const U_CR: char = '\x0D';
/// Reset color mode
///
/// https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#colors--graphics-mode
const COLOR_RESET: &str = "\x1B[0m";
/// Erase cursor till end of line
///
/// https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#erase-functions
const ERASE_CURSOR: &str = "\x1B[0K";
/// A logger that prints log in the format expected by GitLab CI
///
/// See https://docs.gitlab.com/ee/ci/yaml/script.html
pub struct GitLabCILogger {
log_level: LevelFilter,
section_id: Mutex<Option<String>>,
}
impl GitLabCILogger {
pub fn new() -> Self {
// force activation of colors, because GitlabCI does not
// respect the CLICOLORS spec.
// https://gitlab.com/gitlab-org/gitlab/-/issues/28598
console::set_colors_enabled(true);
let log_level = env::var("CODSPEED_LOG")
.ok()
.and_then(|log_level| log_level.parse::<log::LevelFilter>().ok())
.unwrap_or(log::LevelFilter::Info);
Self {
log_level,
section_id: Mutex::new(None),
}
}
}
impl Log for GitLabCILogger {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
if !should_provider_logger_handle_record(record) {
return;
}
let level = record.level();
let message = record.args();
if let Some(group_event) = get_group_event(record) {
let now = SystemTime::now();
let timestamp = now.duration_since(UNIX_EPOCH).unwrap().as_secs();
let mut section_id = self.section_id.lock().unwrap();
match group_event {
GroupEvent::Start(name) | GroupEvent::StartOpened(name) => {
let new_section_id = GITLAB_SECTION_ID_SANITIZE_REGEX
.replace_all(&name, "_")
.to_ascii_lowercase();
*section_id = Some(new_section_id.to_string());
// https://docs.gitlab.com/ee/ci/yaml/script.html#custom-collapsible-sections
println!(
"{ERASE_CURSOR}section_start:{timestamp}:{new_section_id}{U_CR}{ERASE_CURSOR}{U_ESC}[36;1m{name}{COLOR_RESET}"
);
}
GroupEvent::End => {
// do not fail if there is no current section
let current_section_id = section_id.clone().unwrap_or("".to_string());
// https://docs.gitlab.com/ee/ci/yaml/script.html#custom-collapsible-sections
println!(
"{ERASE_CURSOR}section_end:{timestamp}:{current_section_id}{U_CR}{ERASE_CURSOR}"
);
*section_id = None;
}
}
return;
}
if let Some(announcement) = get_announcement_event(record) {
match announcement.title {
Some(title) => println!(
"{}: {}",
style(title).bold().green(),
style(announcement.message).green()
),
None => println!("{}", style(announcement.message).green()),
}
return;
}
if get_json_event(record).is_some() {
return;
}
if level > self.log_level {
return;
}
// set log colors. See https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#colors--graphics-mode
match level {
Level::Error => {
println!("{}", style(message).red());
}
Level::Warn => {
println!("{}", style(message).yellow());
}
Level::Info => {
println!("{message}");
}
Level::Debug => {
println!("{}", style(message).cyan());
}
Level::Trace => {
println!("{}", style(message).magenta());
}
};
}
fn flush(&self) {
std::io::stdout().flush().unwrap();
}
}
impl SharedLogger for GitLabCILogger {
fn level(&self) -> LevelFilter {
self.log_level
}
fn config(&self) -> Option<&simplelog::Config> {
None
}
fn as_log(self: Box<Self>) -> Box<dyn Log> {
Box::new(*self)
}
}