-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathproduct_logging.rs
More file actions
161 lines (143 loc) · 5.08 KB
/
Copy pathproduct_logging.rs
File metadata and controls
161 lines (143 loc) · 5.08 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
use std::fmt::{Display, Write};
use snafu::Snafu;
use stackable_operator::{
builder::configmap::ConfigMapBuilder,
kube::Resource,
product_logging::{
self,
spec::{
AutomaticContainerLogConfig, ContainerLogConfig, ContainerLogConfigChoice, Logging,
},
},
role_utils::RoleGroupRef,
};
use crate::crd::STACKABLE_LOG_DIR;
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("object has no namespace"))]
ObjectHasNoNamespace,
#[snafu(display("failed to retrieve the ConfigMap [{cm_name}]"))]
ConfigMapNotFound {
source: stackable_operator::client::Error,
cm_name: String,
},
#[snafu(display("failed to retrieve the entry [{entry}] for ConfigMap [{cm_name}]"))]
MissingConfigMapEntry {
entry: &'static str,
cm_name: String,
},
#[snafu(display("vectorAggregatorConfigMapName must be set"))]
MissingVectorAggregatorAddress,
}
type Result<T, E = Error> = std::result::Result<T, E>;
const LOG_CONFIG_FILE: &str = "log_config.py";
const LOG_FILE: &str = "airflow.py.json";
/// Extend the ConfigMap with logging and Vector configurations
pub fn extend_config_map_with_log_config<C, K>(
rolegroup: &RoleGroupRef<K>,
logging: &Logging<C>,
main_container: &C,
vector_container: &C,
cm_builder: &mut ConfigMapBuilder,
) -> Result<()>
where
C: Clone + Ord + Display,
K: Resource,
{
if let Some(ContainerLogConfig {
choice: Some(ContainerLogConfigChoice::Automatic(log_config)),
}) = logging.containers.get(main_container)
{
let log_dir = format!("{STACKABLE_LOG_DIR}/{main_container}");
cm_builder.add_data(LOG_CONFIG_FILE, create_airflow_config(log_config, &log_dir));
}
let vector_log_config = if let Some(ContainerLogConfig {
choice: Some(ContainerLogConfigChoice::Automatic(log_config)),
}) = logging.containers.get(vector_container)
{
Some(log_config)
} else {
None
};
if logging.enable_vector_agent {
cm_builder.add_data(
product_logging::framework::VECTOR_CONFIG_FILE,
product_logging::framework::create_vector_config(rolegroup, vector_log_config),
);
}
Ok(())
}
fn create_airflow_config(log_config: &AutomaticContainerLogConfig, log_dir: &str) -> String {
let loggers_config = log_config
.loggers
.iter()
.filter(|(name, _)| name.as_str() != AutomaticContainerLogConfig::ROOT_LOGGER)
.fold(String::new(), |mut output, (name, config)| {
let _ = writeln!(
output,
"
LOGGING_CONFIG['loggers'].setdefault('{name}', {{ 'propagate': True }})
LOGGING_CONFIG['loggers']['{name}']['level'] = {level}
",
level = config.level.to_python_expression()
);
output
});
format!(
"\
import logging
import os
from copy import deepcopy
from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG
os.makedirs('{log_dir}', exist_ok=True)
LOGGING_CONFIG = deepcopy(DEFAULT_LOGGING_CONFIG)
REMOTE_TASK_LOG = None
LOGGING_CONFIG.setdefault('loggers', {{}})
for logger_name, logger_config in LOGGING_CONFIG['loggers'].items():
logger_config['level'] = logging.NOTSET
# Do not change the setting of the airflow.task logger because
# otherwise DAGs cannot be loaded anymore.
if logger_name != 'airflow.task':
logger_config['propagate'] = True
# The default behavior of airflow is to enforce log level 'INFO' on tasks. (https://airflow.apache.org/docs/apache-airflow/stable/configurations-ref.html#logging-level)
# TODO: Make task handler log level configurable through CRDs with default 'INFO'.
# e.g. LOGGING_CONFIG['handlers']['task']['level'] = {{task_log_level}}
if 'handlers' in logger_config and 'task' in logger_config['handlers']:
logger_config['level'] = logging.INFO
LOGGING_CONFIG.setdefault('formatters', {{}})
LOGGING_CONFIG['formatters']['json'] = {{
'()': 'airflow.utils.log.json_formatter.JSONFormatter',
'json_fields': ['asctime', 'levelname', 'message', 'name']
}}
LOGGING_CONFIG.setdefault('handlers', {{}})
LOGGING_CONFIG['handlers'].setdefault('console', {{}})
LOGGING_CONFIG['handlers']['console']['level'] = {console_log_level}
LOGGING_CONFIG['handlers']['file'] = {{
'class': 'logging.handlers.RotatingFileHandler',
'level': {file_log_level},
'formatter': 'json',
'filename': '{log_dir}/{LOG_FILE}',
'maxBytes': 1048576,
'backupCount': 1,
}}
LOGGING_CONFIG['root'] = {{
'level': {root_log_level},
'filters': ['mask_secrets'],
'handlers': ['console', 'file'],
}}
{loggers_config}",
root_log_level = log_config.root_log_level().to_python_expression(),
console_log_level = log_config
.console
.as_ref()
.and_then(|console| console.level)
.unwrap_or_default()
.to_python_expression(),
file_log_level = log_config
.file
.as_ref()
.and_then(|file| file.level)
.unwrap_or_default()
.to_python_expression(),
)
}