-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
functions.py
217 lines (168 loc) · 7.4 KB
/
functions.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import betterproto
from dbt.constants import METADATA_ENV_PREFIX
from dbt.events.base_types import BaseEvent, Cache, EventLevel, NoFile, NoStdOut, EventMsg
from dbt.events.eventmgr import EventManager, LoggerConfig, LineFormat, NoFilter
from dbt.events.helpers import env_secrets, scrub_secrets
from dbt.events.types import EmptyLine
import dbt.flags as flags
from dbt.logger import GLOBAL_LOGGER, make_log_dir_if_missing
from functools import partial
import json
import os
import sys
from typing import Callable, Dict, Optional, TextIO
import uuid
LOG_VERSION = 3
metadata_vars: Optional[Dict[str, str]] = None
def setup_event_logger(log_path: str, level_override: Optional[EventLevel] = None):
cleanup_event_logger()
make_log_dir_if_missing(log_path)
if flags.ENABLE_LEGACY_LOGGER:
EVENT_MANAGER.add_logger(_get_logbook_log_config(level_override))
else:
EVENT_MANAGER.add_logger(_get_stdout_config(level_override))
if _CAPTURE_STREAM:
# Create second stdout logger to support test which want to know what's
# being sent to stdout.
capture_config = _get_stdout_config(level_override)
capture_config.output_stream = _CAPTURE_STREAM
EVENT_MANAGER.add_logger(capture_config)
# create and add the file logger to the event manager
EVENT_MANAGER.add_logger(_get_logfile_config(os.path.join(log_path, "dbt.log")))
def _get_stdout_config(level: Optional[EventLevel] = None) -> LoggerConfig:
fmt = LineFormat.PlainText
if flags.LOG_FORMAT == "json":
fmt = LineFormat.Json
elif flags.DEBUG:
fmt = LineFormat.DebugText
return LoggerConfig(
name="stdout_log",
level=level or (EventLevel.DEBUG if flags.DEBUG else EventLevel.INFO),
use_colors=bool(flags.USE_COLORS),
line_format=fmt,
scrubber=env_scrubber,
filter=partial(
_stdout_filter, bool(flags.LOG_CACHE_EVENTS), bool(flags.DEBUG), bool(flags.QUIET)
),
output_stream=sys.stdout,
)
def _stdout_filter(
log_cache_events: bool, debug_mode: bool, quiet_mode: bool, msg: EventMsg
) -> bool:
return (
not isinstance(msg.data, NoStdOut)
and (not isinstance(msg.data, Cache) or log_cache_events)
and (EventLevel(msg.info.level) != EventLevel.DEBUG or debug_mode)
and (EventLevel(msg.info.level) == EventLevel.ERROR or not quiet_mode)
and not (flags.LOG_FORMAT == "json" and type(msg.data) == EmptyLine)
)
def _get_logfile_config(log_path: str) -> LoggerConfig:
return LoggerConfig(
name="file_log",
line_format=LineFormat.Json if flags.LOG_FORMAT == "json" else LineFormat.DebugText,
use_colors=bool(flags.USE_COLORS),
level=EventLevel.DEBUG, # File log is *always* debug level
scrubber=env_scrubber,
filter=partial(_logfile_filter, bool(flags.LOG_CACHE_EVENTS)),
output_file_name=log_path,
)
def _logfile_filter(log_cache_events: bool, msg: EventMsg) -> bool:
return (
not isinstance(msg.data, NoFile)
and not (isinstance(msg.data, Cache) and not log_cache_events)
and not (flags.LOG_FORMAT == "json" and type(msg.data) == EmptyLine)
)
def _get_logbook_log_config(level: Optional[EventLevel] = None) -> LoggerConfig:
config = _get_stdout_config(level)
config.name = "logbook_log"
config.filter = NoFilter if flags.LOG_CACHE_EVENTS else lambda e: not isinstance(e.data, Cache)
config.logger = GLOBAL_LOGGER
return config
def env_scrubber(msg: str) -> str:
return scrub_secrets(msg, env_secrets())
def cleanup_event_logger():
# Reset to a no-op manager to release streams associated with logs. This is
# especially important for tests, since pytest replaces the stdout stream
# during test runs, and closes the stream after the test is over.
EVENT_MANAGER.loggers.clear()
EVENT_MANAGER.callbacks.clear()
# Since dbt-rpc does not do its own log setup, and since some events can
# currently fire before logs can be configured by setup_event_logger(), we
# create a default configuration with default settings and no file output.
EVENT_MANAGER: EventManager = EventManager()
EVENT_MANAGER.add_logger(
_get_logbook_log_config() if flags.ENABLE_LEGACY_LOGGER else _get_stdout_config()
)
# This global, and the following two functions for capturing stdout logs are
# an unpleasant hack we intend to remove as part of API-ification. The GitHub
# issue #6350 was opened for that work.
_CAPTURE_STREAM: Optional[TextIO] = None
# used for integration tests
def capture_stdout_logs(stream: TextIO):
global _CAPTURE_STREAM
_CAPTURE_STREAM = stream
def stop_capture_stdout_logs():
global _CAPTURE_STREAM
_CAPTURE_STREAM = None
# returns a dictionary representation of the event fields.
# the message may contain secrets which must be scrubbed at the usage site.
def msg_to_json(msg: EventMsg) -> str:
msg_dict = msg_to_dict(msg)
raw_log_line = json.dumps(msg_dict, sort_keys=True)
return raw_log_line
def msg_to_dict(msg: EventMsg) -> dict:
msg_dict = dict()
try:
msg_dict = msg.to_dict(casing=betterproto.Casing.SNAKE, include_default_values=True) # type: ignore
except AttributeError as exc:
event_type = type(msg).__name__
raise Exception(f"type {event_type} is not serializable. {str(exc)}")
# We don't want an empty NodeInfo in output
if (
"data" in msg_dict
and "node_info" in msg_dict["data"]
and msg_dict["data"]["node_info"]["node_name"] == ""
):
del msg_dict["data"]["node_info"]
return msg_dict
def warn_or_error(event, node=None):
# TODO: resolve this circular import when flags.WARN_ERROR_OPTIONS is WarnErrorOptions type via click CLI.
from dbt.helper_types import WarnErrorOptions
warn_error_options = WarnErrorOptions.from_yaml_string(flags.WARN_ERROR_OPTIONS)
if flags.WARN_ERROR or warn_error_options.includes(type(event).__name__):
# TODO: resolve this circular import when at top
from dbt.exceptions import EventCompilationError
raise EventCompilationError(event.message(), node)
else:
fire_event(event)
# an alternative to fire_event which only creates and logs the event value
# if the condition is met. Does nothing otherwise.
def fire_event_if(
conditional: bool, lazy_e: Callable[[], BaseEvent], level: EventLevel = None
) -> None:
if conditional:
fire_event(lazy_e(), level=level)
# top-level method for accessing the new eventing system
# this is where all the side effects happen branched by event type
# (i.e. - mutating the event history, printing to stdout, logging
# to files, etc.)
def fire_event(e: BaseEvent, level: EventLevel = None) -> None:
EVENT_MANAGER.fire_event(e, level=level)
def get_metadata_vars() -> Dict[str, str]:
global metadata_vars
if metadata_vars is None:
metadata_vars = {
k[len(METADATA_ENV_PREFIX) :]: v
for k, v in os.environ.items()
if k.startswith(METADATA_ENV_PREFIX)
}
return metadata_vars
def reset_metadata_vars() -> None:
global metadata_vars
metadata_vars = None
def get_invocation_id() -> str:
return EVENT_MANAGER.invocation_id
def set_invocation_id() -> None:
# This is primarily for setting the invocation_id for separate
# commands in the dbt servers. It shouldn't be necessary for the CLI.
EVENT_MANAGER.invocation_id = str(uuid.uuid4())