Skip to content

Commit 412d7f8

Browse files
authored
Fix issue where setting baml_log would be overwritten (#1732)
<!-- ELLIPSIS_HIDDEN --> > [!IMPORTANT] > Fixes issue with `baml_log` being overwritten by ensuring correct environment variable handling and updates logging initialization and tests. > > - **Behavior**: > - Fix issue where `baml_log` setting was being overwritten by ensuring it is set correctly from environment variables in `baml-runtime/src/lib.rs` and `language_client_python/src/lib.rs`. > - Remove default setting of `BAML_LOG` to "info" in `baml_py/__init__.py`. > - **Logging**: > - Add `init_debug_logger()` function in `language_client_python/src/lib.rs` to initialize a debug logger with `BAML_INTERNAL_LOG`. > - Update tests in `test_logger.py` to verify logger initialization and behavior with different log levels. > - **Misc**: > - Remove unnecessary `load_dotenv()` calls from various test files. > - Add `test-dotenv` file to set `BAML_LOG=warn` for testing purposes. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for 3fbf668. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent 3b6188f commit 412d7f8

14 files changed

Lines changed: 301 additions & 229 deletions

File tree

engine/baml-runtime/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,6 @@ impl BamlRuntime {
180180
.map(|(k, v)| (k.as_ref().to_string(), v.as_ref().to_string()))
181181
.collect();
182182
baml_log::set_from_env(&copy)?;
183-
184183
Ok(BamlRuntime {
185184
inner: InternalBamlRuntime::from_file_content(root_path, files)?,
186185
tracer: BamlTracer::new(None, env_vars.into_iter())?.into(),

engine/language_client_codegen/src/python/templates/__init__.py.j2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ with EnsureBamlPyImport(__version__) as e:
2525
from . import partial_types
2626
from . import config
2727
from .config import reset_baml_env_vars
28-
2928
{% if default_client_mode == GeneratorDefaultClientMode::Async %}
3029
from .async_client import b
3130
{% else %}
@@ -38,5 +37,6 @@ __all__ = [
3837
"tracing",
3938
"types",
4039
"reset_baml_env_vars",
40+
"config",
4141
"logging",
4242
]

engine/language_client_python/python_src/baml_py/__init__.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
# BAML Python API: provides the Python API for the BAML runtime.
22

3-
if __name__ == "baml_py":
4-
import os
5-
6-
if "BAML_LOG" not in os.environ:
7-
os.environ["BAML_LOG"] = "info"
83

94
# Re-export the pyo3 API
105
from .baml_py import (

engine/language_client_python/src/lib.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ fn baml_py(m: Bound<'_, PyModule>) -> PyResult<()> {
8686

8787
// Initialize the logger
8888
baml_log::init().map_err(errors::BamlError::from_anyhow)?;
89-
89+
init_debug_logger();
9090
Ok(())
9191
}
92+
93+
fn init_debug_logger() {
94+
// Regular formatting
95+
if let Err(e) =
96+
env_logger::try_init_from_env(env_logger::Env::new().filter("BAML_INTERNAL_LOG"))
97+
{
98+
println!("Failed to initialize BAML DEBUG logger: {:#}", e);
99+
}
100+
}

integ-tests/python/baml_client/__init__.py

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 60 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,78 @@
11
import time
22
import threading
33
import asyncio
4-
from dotenv import load_dotenv
54
from http.server import BaseHTTPRequestHandler, HTTPServer
65
import json
76
import os
87
from baml_client.tracing import trace, flush
98

10-
load_dotenv()
11-
os.environ['BOUNDARY_BASE_URL'] = 'http://localhost:4040'
9+
os.environ["BOUNDARY_BASE_URL"] = "http://localhost:4040"
1210

13-
class TraceRequestHandler(BaseHTTPRequestHandler):
1411

12+
class TraceRequestHandler(BaseHTTPRequestHandler):
1513
@staticmethod
1614
def run_forever():
17-
address = ('', int(os.environ['BOUNDARY_BASE_URL'].rsplit(':', maxsplit=1)[1]))
18-
httpd = HTTPServer(address, TraceRequestHandler)
19-
print(f'Starting BAML event logger on {address}')
20-
httpd.serve_forever()
21-
15+
address = ("", int(os.environ["BOUNDARY_BASE_URL"].rsplit(":", maxsplit=1)[1]))
16+
httpd = HTTPServer(address, TraceRequestHandler)
17+
print(f"Starting BAML event logger on {address}")
18+
httpd.serve_forever()
2219

2320
def do_GET(self):
24-
print(f"Received GET request: {self.path}")
25-
# self.send_response(200)
26-
# self.send_header('Content-type', 'text/html')
27-
# #self.send_header('Content-type', 'application/json')
28-
# self.end_headers()
29-
# self.wfile.write('Hello, BAML!'.encode('utf-8'))
30-
self.send_error(404, "File not found")
21+
print(f"Received GET request: {self.path}")
22+
# self.send_response(200)
23+
# self.send_header('Content-type', 'text/html')
24+
# #self.send_header('Content-type', 'application/json')
25+
# self.end_headers()
26+
# self.wfile.write('Hello, BAML!'.encode('utf-8'))
27+
self.send_error(404, "File not found")
3128

3229
def do_POST(self):
33-
print(f"Received POST request: {self.path}")
34-
self.send_error(404, "File not found")
35-
return
36-
if self.path == '/log/v2':
37-
content_length = int(self.headers['Content-Length']) # Get the size of data
38-
post_data = self.rfile.read(content_length) # Read the data
39-
data = json.loads(post_data.decode('utf-8')) # Decode it to string
40-
41-
print(f"Received event log for {data}")
42-
print(json.dumps(data, indent=2))
43-
44-
self.send_response(200)
45-
self.send_header('Content-type', 'application/json')
46-
self.end_headers()
47-
response = json.dumps({'message': 'Log received'})
48-
self.wfile.write(response.encode('utf-8')) # Send response back to client
49-
else:
50-
self.send_error(404, "File not found")
30+
print(f"Received POST request: {self.path}")
31+
self.send_error(404, "File not found")
32+
return
33+
if self.path == "/log/v2":
34+
content_length = int(self.headers["Content-Length"]) # Get the size of data
35+
post_data = self.rfile.read(content_length) # Read the data
36+
data = json.loads(post_data.decode("utf-8")) # Decode it to string
37+
38+
print(f"Received event log for {data}")
39+
print(json.dumps(data, indent=2))
40+
41+
self.send_response(200)
42+
self.send_header("Content-type", "application/json")
43+
self.end_headers()
44+
response = json.dumps({"message": "Log received"})
45+
self.wfile.write(response.encode("utf-8")) # Send response back to client
46+
else:
47+
self.send_error(404, "File not found")
48+
5149

5250
async def main():
53-
print('Hello, BAML!')
54-
#TraceRequestHandler.run_forever()
55-
t = threading.Thread(target=TraceRequestHandler.run_forever, daemon=True)
56-
t.start()
57-
58-
print('waiting for server to start')
59-
time.sleep(5)
60-
print('server has started ( i think )')
61-
62-
@trace
63-
def sync_dummy_fn():
64-
time.sleep(.05)
65-
66-
sync_dummy_fn()
67-
68-
print('before flush')
69-
t_flush = threading.Thread(target=flush)
70-
print('wtf?')
71-
t_flush.start()
72-
print('after start before join')
73-
t_flush.join(timeout=5)
74-
print('after flush')
75-
76-
assert False
77-
78-
if __name__ == '__main__':
79-
asyncio.run(main())
51+
print("Hello, BAML!")
52+
# TraceRequestHandler.run_forever()
53+
t = threading.Thread(target=TraceRequestHandler.run_forever, daemon=True)
54+
t.start()
55+
56+
print("waiting for server to start")
57+
time.sleep(5)
58+
print("server has started ( i think )")
59+
60+
@trace
61+
def sync_dummy_fn():
62+
time.sleep(0.05)
63+
64+
sync_dummy_fn()
65+
66+
print("before flush")
67+
t_flush = threading.Thread(target=flush)
68+
print("wtf?")
69+
t_flush.start()
70+
print("after start before join")
71+
t_flush.join(timeout=5)
72+
print("after flush")
73+
74+
assert False
75+
76+
77+
if __name__ == "__main__":
78+
asyncio.run(main())

integ-tests/python/test-dotenv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# assume tests run from this directory.
2+
# Dont change this. It will get picked up by test_logger.py
3+
BAML_LOG=warn

integ-tests/python/tests/test_collector.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from baml_py.errors import BamlInvalidArgumentError, BamlError, BamlClientError
22
import pytest
3-
import dotenv
43
from openai.types.chat import ChatCompletion
54

65
from ..baml_client import b
@@ -10,8 +9,6 @@
109
import sys
1110
import asyncio
1211

13-
dotenv.load_dotenv()
14-
1512

1613
def function_span_count():
1714
return Collector.__function_span_count() # type: ignore

0 commit comments

Comments
 (0)