-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathlogs.py
346 lines (272 loc) · 10.5 KB
/
logs.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# Copyright (c) 2024 Airbyte, Inc., all rights reserved.
"""PyAirbyte Logging features and related configuration.
By default, PyAirbyte main logs are written to a file in the `AIRBYTE_LOGGING_ROOT` directory, which
defaults to a system-created temporary directory. PyAirbyte also maintains connector-specific log
files within the same directory, under a subfolder with the name of the connector.
PyAirbyte supports structured JSON logging, which is disabled by default. To enable structured
logging in JSON, set `AIRBYTE_STRUCTURED_LOGGING` to `True`.
"""
from __future__ import annotations
import logging
import os
import platform
import tempfile
import warnings
from functools import lru_cache
from pathlib import Path
import structlog
import ulid
from airbyte_cdk.utils.datetime_helpers import ab_datetime_now
def _str_to_bool(value: str) -> bool:
"""Convert a string value of an environment values to a boolean value."""
return bool(value) and value.lower() not in {"", "0", "false", "f", "no", "n", "off"}
AIRBYTE_STRUCTURED_LOGGING: bool = _str_to_bool(
os.getenv(
key="AIRBYTE_STRUCTURED_LOGGING",
default="false",
)
)
"""Whether to enable structured logging.
This value is read from the `AIRBYTE_STRUCTURED_LOGGING` environment variable. If the variable is
not set, the default value is `False`.
"""
_warned_messages: set[str] = set()
def warn_once(
message: str,
logger: logging.Logger | None = None,
*,
with_stack: int | bool,
) -> None:
"""Emit a warning message only once.
This function is a wrapper around the `warnings.warn` function that logs the warning message
to the global logger. The warning message is only emitted once per unique message.
"""
if message in _warned_messages:
return
if not with_stack:
stacklevel = 0
if with_stack is True:
stacklevel = 2
_warned_messages.add(message)
warnings.warn(
message,
category=UserWarning,
stacklevel=stacklevel,
)
if logger:
logger.warning(message)
def _get_logging_root() -> Path | None:
"""Return the root directory for logs.
Returns `None` if no valid path can be found.
This is the directory where logs are stored.
"""
if "AIRBYTE_LOGGING_ROOT" in os.environ:
log_root = Path(os.environ["AIRBYTE_LOGGING_ROOT"])
elif platform.system() == "Darwin" or platform.system() == "Linux":
# Use /tmp on macOS and Linux
log_root = Path("/tmp") / "airbyte" / "logs"
else:
# Use the default temp directory on Windows or any other OS
log_root = Path(tempfile.gettempdir()) / "airbyte" / "logs"
try:
# Attempt to create the log root directory if it does not exist
log_root.mkdir(parents=True, exist_ok=True)
except OSError:
# Handle the error by returning None
warn_once(
(
f"Failed to create PyAirbyte logging directory at `{log_root}`. "
"You can override the default path by setting the `AIRBYTE_LOGGING_ROOT` "
"environment variable."
),
with_stack=False,
)
return None
else:
return log_root
AIRBYTE_LOGGING_ROOT: Path | None = _get_logging_root()
"""The root directory for Airbyte logs.
This value can be overridden by setting the `AIRBYTE_LOGGING_ROOT` environment variable.
If not provided, PyAirbyte will use `/tmp/airbyte/logs/` where `/tmp/` is the OS's default
temporary directory. If the directory cannot be created, PyAirbyte will log a warning and
set this value to `None`.
"""
@lru_cache
def get_global_file_logger() -> logging.Logger | None:
"""Return the global logger for PyAirbyte.
This logger is configured to write logs to the console and to a file in the log directory.
"""
logger = logging.getLogger("airbyte")
logger.setLevel(logging.INFO)
logger.propagate = False
if AIRBYTE_LOGGING_ROOT is None:
# No temp directory available, so return None
return None
# Else, configure the logger to write to a file
# Remove any existing handlers
for handler in logger.handlers:
logger.removeHandler(handler)
yyyy_mm_dd: str = ab_datetime_now().strftime("%Y-%m-%d")
folder = AIRBYTE_LOGGING_ROOT / yyyy_mm_dd
try:
folder.mkdir(parents=True, exist_ok=True)
except Exception:
warn_once(
f"Failed to create logging directory at '{folder!s}'.",
with_stack=False,
)
return None
logfile_path = folder / f"airbyte-log-{str(ulid.ULID())[2:11]}.log"
print(f"Writing PyAirbyte logs to file: {logfile_path!s}")
file_handler = logging.FileHandler(
filename=logfile_path,
encoding="utf-8",
)
if AIRBYTE_STRUCTURED_LOGGING:
# Create a formatter and set it for the handler
formatter = logging.Formatter("%(message)s")
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# Configure structlog
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.JSONRenderer(),
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
# Create a logger
return structlog.get_logger("airbyte")
# Create and configure file handler
file_handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger.addHandler(file_handler)
return logger
def get_global_stats_log_path() -> Path | None:
"""Return the path to the performance log file."""
if AIRBYTE_LOGGING_ROOT is None:
return None
folder = AIRBYTE_LOGGING_ROOT
try:
folder.mkdir(parents=True, exist_ok=True)
except Exception:
warn_once(
f"Failed to create logging directory at '{folder!s}'.",
with_stack=False,
)
return None
return folder / "airbyte-stats.log"
@lru_cache
def get_global_stats_logger() -> structlog.BoundLogger:
"""Create a stats logger for performance metrics."""
logger = logging.getLogger("airbyte.stats")
logger.setLevel(logging.INFO)
logger.propagate = False
# Configure structlog
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.JSONRenderer(),
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
logfile_path: Path | None = get_global_stats_log_path()
if AIRBYTE_LOGGING_ROOT is None or logfile_path is None:
# No temp directory available, so return no-op logger without handlers
return structlog.get_logger("airbyte.stats")
print(f"Writing PyAirbyte performance stats to file: {logfile_path!s}")
# Remove any existing handlers
for handler in logger.handlers:
logger.removeHandler(handler)
folder = AIRBYTE_LOGGING_ROOT
try:
folder.mkdir(parents=True, exist_ok=True)
except Exception:
warn_once(
f"Failed to create logging directory at '{folder!s}'.",
with_stack=False,
)
return structlog.get_logger("airbyte.stats")
file_handler = logging.FileHandler(
filename=logfile_path,
encoding="utf-8",
)
# Create a formatter and set it for the handler
formatter = logging.Formatter("%(message)s")
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# Create a logger
return structlog.get_logger("airbyte.stats")
def new_passthrough_file_logger(connector_name: str) -> logging.Logger:
"""Create a logger from logging module."""
logger = logging.getLogger(f"airbyte.{connector_name}")
logger.setLevel(logging.INFO)
# Prevent logging to stderr by stopping propagation to the root logger
logger.propagate = False
if AIRBYTE_LOGGING_ROOT is None:
# No temp directory available, so return a basic logger
return logger
# Else, configure the logger to write to a file
# Remove any existing handlers
for handler in logger.handlers:
logger.removeHandler(handler)
folder = AIRBYTE_LOGGING_ROOT / connector_name
folder.mkdir(parents=True, exist_ok=True)
# Create a file handler
global_logger = get_global_file_logger()
logfile_path = folder / f"{connector_name}-log-{str(ulid.ULID())[2:11]}.log"
logfile_msg = f"Writing `{connector_name}` logs to file: {logfile_path!s}"
print(logfile_msg)
if global_logger:
global_logger.info(logfile_msg)
file_handler = logging.FileHandler(logfile_path)
file_handler.setLevel(logging.INFO)
if AIRBYTE_STRUCTURED_LOGGING:
# Create a formatter and set it for the handler
formatter = logging.Formatter("%(message)s")
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# Configure structlog
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.JSONRenderer(),
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
# Create a logger
return structlog.get_logger(f"airbyte.{connector_name}")
# Else, write logs in plain text
file_handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger.addHandler(file_handler)
return logger