metaflow-logs 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ name: Test (Python ${{ matrix.python-version }})
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
17
+
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+
21
+ - name: Set up Python ${{ matrix.python-version }}
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: ${{ matrix.python-version }}
25
+
26
+ - name: Install package and test dependencies
27
+ run: |
28
+ pip install -e .
29
+ pip install -r tests/requirements.in
30
+
31
+ - name: Run tests
32
+ run: pytest tests/ -v --tb=short
33
+
34
+ lint:
35
+ name: Lint
36
+ runs-on: ubuntu-latest
37
+
38
+ steps:
39
+ - uses: actions/checkout@v4
40
+
41
+ - name: Set up Python
42
+ uses: actions/setup-python@v5
43
+ with:
44
+ python-version: "3.12"
45
+
46
+ - name: Install ruff
47
+ run: pip install ruff
48
+
49
+ - name: Check formatting
50
+ run: ruff format --check src tests
51
+
52
+ - name: Check lint
53
+ run: ruff check src tests
54
+
55
+ typecheck:
56
+ name: Type check
57
+ runs-on: ubuntu-latest
58
+
59
+ steps:
60
+ - uses: actions/checkout@v4
61
+
62
+ - name: Set up Python
63
+ uses: actions/setup-python@v5
64
+ with:
65
+ python-version: "3.12"
66
+
67
+ - name: Install dependencies
68
+ run: |
69
+ pip install -e .
70
+ pip install mypy
71
+
72
+ - name: Run mypy
73
+ run: mypy src
@@ -0,0 +1,47 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+ id-token: write # required for OIDC trusted publishing
10
+
11
+ jobs:
12
+ build:
13
+ name: Build distribution
14
+ runs-on: ubuntu-latest
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - uses: actions/setup-python@v5
20
+ with:
21
+ python-version: "3.12"
22
+
23
+ - name: Install build backend
24
+ run: pip install build
25
+
26
+ - name: Build wheel and sdist
27
+ run: python -m build
28
+
29
+ - uses: actions/upload-artifact@v4
30
+ with:
31
+ name: dist
32
+ path: dist/
33
+
34
+ publish:
35
+ name: Publish to PyPI
36
+ needs: build
37
+ runs-on: ubuntu-latest
38
+ environment: pypi
39
+
40
+ steps:
41
+ - uses: actions/download-artifact@v4
42
+ with:
43
+ name: dist
44
+ path: dist/
45
+
46
+ - name: Publish to PyPI
47
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,41 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ *.egg
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ .eggs/
11
+ *.whl
12
+
13
+ # Virtual environments
14
+ .venv/
15
+ venv/
16
+ env/
17
+ .env
18
+
19
+ # Tox / testing
20
+ .tox/
21
+ .pytest_cache/
22
+ .coverage
23
+ coverage.xml
24
+ htmlcov/
25
+ *.cover
26
+
27
+ # Mypy
28
+ .mypy_cache/
29
+ .dmypy.json
30
+
31
+ # Ruff
32
+ .ruff_cache/
33
+
34
+ # Hatch
35
+ .hatch/
36
+
37
+ # IDE
38
+ .idea/
39
+ .vscode/
40
+ *.swp
41
+ *.swo
@@ -0,0 +1,184 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submit" means any form of electronic, verbal, or
51
+ written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of clarifying or
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes patent infringement,
82
+ then any patent licenses granted to You under this License for that
83
+ Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or in addition with
114
+ the NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the
116
+ License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional terms and conditions for use, reproduction,
120
+ or modification of Your modifications, beyond those set out in this
121
+ License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms and conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of TITLE,
141
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
142
+ PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and are responsible
144
+ for any risks associated with Your exercise of permissions under
145
+ this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial and commercial damages or losses), even if such
157
+ Contributor has been advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may wish to offer, and
161
+ charge a fee for, acceptance of support, warranty, indemnity, or
162
+ other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may offer only
164
+ conditions that are your own account and sole responsibility, not on
165
+ behalf of any other Contributor, and only if You agree to indemnify,
166
+ defend, and hold each Contributor harmless for any liability incurred
167
+ by, or claims asserted against, such Contributor by reason of your
168
+ accepting any such warranty or additional liability.
169
+
170
+ END OF TERMS AND CONDITIONS
171
+
172
+ Copyright 2024 Nissan Pow
173
+
174
+ Licensed under the Apache License, Version 2.0 (the "License");
175
+ you may not use this file except in compliance with the License.
176
+ You may obtain a copy of the License at
177
+
178
+ http://www.apache.org/licenses/LICENSE-2.0
179
+
180
+ Unless required by applicable law or agreed to in writing, software
181
+ distributed under the License is distributed on an "AS IS" BASIS,
182
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183
+ See the License for the specific language governing permissions and
184
+ limitations under the License.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: metaflow-logs
3
+ Version: 0.1.0
4
+ Summary: Ships Metaflow task logs to a centralized backend via OpenTelemetry
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: metaflow>=2.9
9
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24
10
+ Requires-Dist: opentelemetry-sdk>=1.24
11
+ Description-Content-Type: text/markdown
12
+
13
+ # metaflow-logs
14
+
15
+ [![CI](https://img.shields.io/github/actions/workflow/status/npow/metaflow-logs/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/npow/metaflow-logs/actions/workflows/ci.yml)
16
+ [![PyPI](https://img.shields.io/pypi/v/metaflow-logs?style=flat-square)](https://pypi.org/project/metaflow-logs/)
17
+ [![Python](https://img.shields.io/pypi/pyversions/metaflow-logs?style=flat-square)](https://pypi.org/project/metaflow-logs/)
18
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE)
19
+
20
+ A Metaflow extension that ships task stdout and stderr to any [OpenTelemetry](https://opentelemetry.io/)-compatible backend (Grafana Loki, Datadog, New Relic, Elasticsearch, Honeycomb, …). Each log line is tagged with full task context — flow name, run ID, step name, task ID, attempt — making logs filterable and correlatable from any OTel-aware tool.
21
+
22
+ ## Quick start
23
+
24
+ ```bash
25
+ pip install metaflow-logs
26
+ ```
27
+
28
+ Add the decorator to any step:
29
+
30
+ ```python
31
+ from metaflow import FlowSpec, step
32
+ from metaflow_extensions.logs.plugins.decorator import LogsDecorator
33
+
34
+ class MyFlow(FlowSpec):
35
+ @LogsDecorator()
36
+ @step
37
+ def train(self):
38
+ print("epoch 1 complete")
39
+ self.next(self.end)
40
+
41
+ @step
42
+ def end(self):
43
+ pass
44
+
45
+ if __name__ == "__main__":
46
+ MyFlow()
47
+ ```
48
+
49
+ Point it at your OTel collector:
50
+
51
+ ```bash
52
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
53
+ python flow.py run
54
+ ```
55
+
56
+ Each log line arrives in your backend tagged with:
57
+
58
+ | Attribute | Example |
59
+ |-----------|---------|
60
+ | `metaflow.flow` | `MyFlow` |
61
+ | `metaflow.run_id` | `123` |
62
+ | `metaflow.step` | `train` |
63
+ | `metaflow.task_id` | `456` |
64
+ | `metaflow.attempt` | `0` |
65
+ | `metaflow.log_source` | `task` or `runtime` |
66
+
67
+ ## Configuration
68
+
69
+ All configuration is via standard OTel environment variables:
70
+
71
+ | Variable | Default | Purpose |
72
+ |----------|---------|---------|
73
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTel collector endpoint |
74
+ | `OTEL_EXPORTER_OTLP_HEADERS` | — | Auth headers (e.g. `Authorization=Bearer ...`) |
75
+ | `OTEL_SERVICE_NAME` | `metaflow` | Service name in your backend |
76
+
77
+ Falls back to a console exporter if `opentelemetry-exporter-otlp-proto-http` is not installed.
78
+
79
+ ## How it works
80
+
81
+ Reads Metaflow's structured MFLOG files (`MFLOG_STDOUT`, `MFLOG_STDERR`) at step completion and emits each line as an OTel `LogRecord`. Runtime logs (Metaflow internals) are emitted at `DEBUG` severity; task logs (your code's stdout/stderr) at `INFO`.
82
+
83
+ ## Development
84
+
85
+ ```bash
86
+ git clone https://github.com/npow/metaflow-logs
87
+ cd metaflow-logs
88
+ pip install -e .
89
+ pytest tests/ -v
90
+ ```
@@ -0,0 +1,78 @@
1
+ # metaflow-logs
2
+
3
+ [![CI](https://img.shields.io/github/actions/workflow/status/npow/metaflow-logs/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/npow/metaflow-logs/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/metaflow-logs?style=flat-square)](https://pypi.org/project/metaflow-logs/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/metaflow-logs?style=flat-square)](https://pypi.org/project/metaflow-logs/)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE)
7
+
8
+ A Metaflow extension that ships task stdout and stderr to any [OpenTelemetry](https://opentelemetry.io/)-compatible backend (Grafana Loki, Datadog, New Relic, Elasticsearch, Honeycomb, …). Each log line is tagged with full task context — flow name, run ID, step name, task ID, attempt — making logs filterable and correlatable from any OTel-aware tool.
9
+
10
+ ## Quick start
11
+
12
+ ```bash
13
+ pip install metaflow-logs
14
+ ```
15
+
16
+ Add the decorator to any step:
17
+
18
+ ```python
19
+ from metaflow import FlowSpec, step
20
+ from metaflow_extensions.logs.plugins.decorator import LogsDecorator
21
+
22
+ class MyFlow(FlowSpec):
23
+ @LogsDecorator()
24
+ @step
25
+ def train(self):
26
+ print("epoch 1 complete")
27
+ self.next(self.end)
28
+
29
+ @step
30
+ def end(self):
31
+ pass
32
+
33
+ if __name__ == "__main__":
34
+ MyFlow()
35
+ ```
36
+
37
+ Point it at your OTel collector:
38
+
39
+ ```bash
40
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
41
+ python flow.py run
42
+ ```
43
+
44
+ Each log line arrives in your backend tagged with:
45
+
46
+ | Attribute | Example |
47
+ |-----------|---------|
48
+ | `metaflow.flow` | `MyFlow` |
49
+ | `metaflow.run_id` | `123` |
50
+ | `metaflow.step` | `train` |
51
+ | `metaflow.task_id` | `456` |
52
+ | `metaflow.attempt` | `0` |
53
+ | `metaflow.log_source` | `task` or `runtime` |
54
+
55
+ ## Configuration
56
+
57
+ All configuration is via standard OTel environment variables:
58
+
59
+ | Variable | Default | Purpose |
60
+ |----------|---------|---------|
61
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTel collector endpoint |
62
+ | `OTEL_EXPORTER_OTLP_HEADERS` | — | Auth headers (e.g. `Authorization=Bearer ...`) |
63
+ | `OTEL_SERVICE_NAME` | `metaflow` | Service name in your backend |
64
+
65
+ Falls back to a console exporter if `opentelemetry-exporter-otlp-proto-http` is not installed.
66
+
67
+ ## How it works
68
+
69
+ Reads Metaflow's structured MFLOG files (`MFLOG_STDOUT`, `MFLOG_STDERR`) at step completion and emits each line as an OTel `LogRecord`. Runtime logs (Metaflow internals) are emitted at `DEBUG` severity; task logs (your code's stdout/stderr) at `INFO`.
70
+
71
+ ## Development
72
+
73
+ ```bash
74
+ git clone https://github.com/npow/metaflow-logs
75
+ cd metaflow-logs
76
+ pip install -e .
77
+ pytest tests/ -v
78
+ ```
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "metaflow-logs"
7
+ version = "0.1.0"
8
+ description = "Ships Metaflow task logs to a centralized backend via OpenTelemetry"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "Apache-2.0" }
12
+ dependencies = [
13
+ "metaflow>=2.9",
14
+ "opentelemetry-sdk>=1.24",
15
+ "opentelemetry-exporter-otlp-proto-http>=1.24",
16
+ ]
17
+
18
+ [project.entry-points."metaflow_extensions"]
19
+ logs = "metaflow_extensions.logs"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/metaflow_extensions"]
23
+
24
+ [tool.pytest.ini_options]
25
+ testpaths = ["tests"]
26
+
27
+ [tool.ruff]
28
+ line-length = 100
29
+ target-version = "py39"
30
+
31
+ [tool.ruff.lint]
32
+ select = ["E", "F", "I", "UP"]
33
+
34
+ [tool.mypy]
35
+ python_version = "3.9"
36
+ strict = true
37
+ disallow_subclassing_any = false
38
+
39
+ [[tool.mypy.overrides]]
40
+ module = ["metaflow.*", "opentelemetry.*"]
41
+ ignore_missing_imports = true
@@ -0,0 +1,5 @@
1
+ """metaflow-logs: ships Metaflow task logs to a centralized OTel backend."""
2
+
3
+ from .plugins.decorator import LogsDecorator
4
+
5
+ STEP_DECORATORS = [LogsDecorator]
@@ -0,0 +1,10 @@
1
+ """OTel attribute name constants for Metaflow log records."""
2
+
3
+ ATTR_FLOW = "metaflow.flow"
4
+ ATTR_RUN_ID = "metaflow.run_id"
5
+ ATTR_STEP = "metaflow.step"
6
+ ATTR_TASK_ID = "metaflow.task_id"
7
+ ATTR_ATTEMPT = "metaflow.attempt"
8
+ ATTR_LOG_SOURCE = "metaflow.log_source"
9
+
10
+ SERVICE_NAME = "metaflow"
@@ -0,0 +1,104 @@
1
+ """Metaflow step decorator that ships task logs to an OTel backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Callable
7
+
8
+ from metaflow.decorators import StepDecorator
9
+
10
+ from .attrs import ATTR_ATTEMPT, ATTR_FLOW, ATTR_RUN_ID, ATTR_STEP, ATTR_TASK_ID
11
+ from .exporter import LogShipper, TaskAttributes, make_logger_provider
12
+ from .mflog_parser import parse_stream
13
+
14
+ _LOG_ENV_VARS = ("MFLOG_STDOUT", "MFLOG_STDERR")
15
+
16
+
17
+ class LogsDecorator(StepDecorator):
18
+ """Ships task stdout and stderr to an OpenTelemetry Logs backend.
19
+
20
+ Applied per-step::
21
+
22
+ @logs
23
+ @step
24
+ def train(self):
25
+ ...
26
+
27
+ Configure the export endpoint with standard OTel environment variables
28
+ (``OTEL_EXPORTER_OTLP_ENDPOINT``, etc.). Log records carry Metaflow
29
+ task context as OTel attributes (flow, run_id, step, task_id, attempt).
30
+ """
31
+
32
+ name = "logs"
33
+ defaults: dict[str, Any] = {}
34
+
35
+ def __init__(
36
+ self,
37
+ *args: Any,
38
+ provider_factory: Callable[[TaskAttributes], Any] | None = None,
39
+ **kwargs: Any,
40
+ ) -> None:
41
+ super().__init__(*args, **kwargs) # type: ignore[no-untyped-call]
42
+ self._provider_factory = provider_factory or make_logger_provider
43
+ self._shipper: LogShipper | None = None
44
+ self._provider: Any | None = None
45
+ self._task_attrs: TaskAttributes = {}
46
+
47
+ def task_pre_step(
48
+ self,
49
+ step_name: str,
50
+ task_datastore: Any,
51
+ metadata: Any,
52
+ run_id: str,
53
+ task_id: str,
54
+ flow: Any,
55
+ graph: Any,
56
+ retry_count: int,
57
+ max_user_code_retries: int,
58
+ ubf_context: Any,
59
+ inputs: Any,
60
+ ) -> None:
61
+ self._task_attrs = {
62
+ ATTR_FLOW: flow.__class__.__name__,
63
+ ATTR_RUN_ID: str(run_id),
64
+ ATTR_STEP: step_name,
65
+ ATTR_TASK_ID: str(task_id),
66
+ ATTR_ATTEMPT: str(retry_count),
67
+ }
68
+ self._provider = self._provider_factory(self._task_attrs)
69
+ self._shipper = LogShipper(self._provider)
70
+
71
+ def task_post_step(
72
+ self,
73
+ step_name: str,
74
+ flow: Any,
75
+ graph: Any,
76
+ retry_count: int,
77
+ max_user_code_retries: int,
78
+ ) -> None:
79
+ self._emit_and_flush()
80
+
81
+ def task_exception(
82
+ self,
83
+ exception: Exception,
84
+ step_name: str,
85
+ flow: Any,
86
+ graph: Any,
87
+ retry_count: int,
88
+ max_user_code_retries: int,
89
+ ) -> None:
90
+ self._emit_and_flush()
91
+
92
+ def _emit_and_flush(self) -> None:
93
+ if self._shipper is None:
94
+ return
95
+ for env_var in _LOG_ENV_VARS:
96
+ path = os.environ.get(env_var)
97
+ if path and os.path.exists(path):
98
+ with open(path, "rb") as fh:
99
+ for line in parse_stream(fh.read()):
100
+ self._shipper.ship(line, self._task_attrs)
101
+ if self._provider is not None:
102
+ self._provider.shutdown()
103
+ self._shipper = None
104
+ self._provider = None