Skip to content

Commit 6bc62d3

Browse files
committed
refactor(logging): use lazy %-style formatting in log calls
1 parent e9fbe50 commit 6bc62d3

22 files changed

Lines changed: 351 additions & 177 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ If you change CI bootstrap:
147147
## Python-Specific Notes
148148

149149
- Exception messages should not inline f-string literals in the `raise` statement. Build the message in a variable first.
150+
- Logging calls must not use f-strings; pass lazy `%`-style args (`langfuse_logger.debug("span=%s", name)`), enforced by ruff `G004`. Arguments are still evaluated eagerly, so guard an expensive one with `langfuse_logger.isEnabledFor(logging.DEBUG)`.
150151
- Prefer ASCII-only edits unless the file already uses Unicode or Unicode is clearly required.
151152

152153
## Release And Docs

‎code_review.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Use this checklist for `/review`, PR review, or self-review before handoff.
3333
## Python Style
3434

3535
- Exception messages should not inline f-string literals in `raise` statements; build the message in a variable first.
36+
- Logging calls should use lazy `%`-style args, not f-strings (ruff `G004`). Flag any logging argument that is expensive to compute and is not behind an `isEnabledFor` guard.
3637
- Keep edits ASCII-only unless the file already uses Unicode or Unicode is clearly required.
3738
- Keep changes scoped; avoid opportunistic refactors.
3839
- Never commit secrets or credentials.

‎langfuse/_client/client.py‎

Lines changed: 60 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,7 +1200,7 @@ def start_as_current_observation(
12001200

12011201
# This should never be reached since all valid types are handled above
12021202
langfuse_logger.warning(
1203-
f"Unknown observation type: {as_type}, falling back to span"
1203+
"Unknown observation type: %s, falling back to span", as_type
12041204
)
12051205
return self._start_as_current_otel_span_with_processed_media(
12061206
as_type="span",
@@ -1734,12 +1734,16 @@ def _create_remote_parent_span(
17341734
) -> Any:
17351735
if not self._is_valid_trace_id(trace_id):
17361736
langfuse_logger.warning(
1737-
f"Passed trace ID '{trace_id}' is not a valid 32 lowercase hex char Langfuse trace id. Ignoring trace ID."
1737+
"Passed trace ID '%s' is not a valid 32 lowercase hex char Langfuse trace "
1738+
"id. Ignoring trace ID.",
1739+
trace_id,
17381740
)
17391741

17401742
if parent_span_id and not self._is_valid_span_id(parent_span_id):
17411743
langfuse_logger.warning(
1742-
f"Passed span ID '{parent_span_id}' is not a valid 16 lowercase hex char Langfuse span id. Ignoring parent span ID."
1744+
"Passed span ID '%s' is not a valid 16 lowercase hex char Langfuse span "
1745+
"id. Ignoring parent span ID.",
1746+
parent_span_id,
17431747
)
17441748

17451749
int_trace_id = int(trace_id, 16)
@@ -2051,7 +2055,11 @@ def create_score(
20512055

20522056
except Exception as e:
20532057
langfuse_logger.exception(
2054-
f"Error creating score: Failed to process score event for trace_id={trace_id}, name={name}. Error: {e}"
2058+
"Error creating score: Failed to process score event for trace_id=%s, "
2059+
"name=%s. Error: %s",
2060+
trace_id,
2061+
name,
2062+
e,
20552063
)
20562064

20572065
def _create_trace_tags_via_ingestion(
@@ -2084,7 +2092,10 @@ def _create_trace_tags_via_ingestion(
20842092
self._resources.add_trace_task(event)
20852093
except Exception as e:
20862094
langfuse_logger.exception(
2087-
f"Error updating trace tags: Failed to process trace update event for trace_id={trace_id}. Error: {e}"
2095+
"Error updating trace tags: Failed to process trace update event for "
2096+
"trace_id=%s. Error: %s",
2097+
trace_id,
2098+
e,
20882099
)
20892100

20902101
@overload
@@ -2167,7 +2178,12 @@ def score_current_span(
21672178
observation_id = self._get_otel_span_id(current_span)
21682179

21692180
langfuse_logger.info(
2170-
f"Score: Creating score name='{name}' value={value} for current span ({observation_id}) in trace {trace_id}"
2181+
"Score: Creating score name='%s' value=%s for current span (%s) in trace "
2182+
"%s",
2183+
name,
2184+
value,
2185+
observation_id,
2186+
trace_id,
21712187
)
21722188

21732189
self.create_score(
@@ -2265,7 +2281,10 @@ def score_current_trace(
22652281
trace_id = self._get_otel_trace_id(current_span)
22662282

22672283
langfuse_logger.info(
2268-
f"Score: Creating score name='{name}' value={value} for entire trace {trace_id}"
2284+
"Score: Creating score name='%s' value=%s for entire trace %s",
2285+
name,
2286+
value,
2287+
trace_id,
22692288
)
22702289

22712290
self.create_score(
@@ -2476,7 +2495,7 @@ def get_dataset(
24762495
DatasetClient: The dataset with the given name.
24772496
"""
24782497
try:
2479-
langfuse_logger.debug(f"Getting datasets {name}")
2498+
langfuse_logger.debug("Getting datasets %s", name)
24802499
dataset = self.api.datasets.get(dataset_name=self._url_encode(name))
24812500

24822501
dataset_items: List[DatasetItem] = []
@@ -2804,7 +2823,7 @@ async def _run_experiment_async(
28042823
dataset_version: Optional[datetime] = None,
28052824
) -> ExperimentResult:
28062825
langfuse_logger.debug(
2807-
f"Starting experiment '{name}' run '{run_name}' with {len(data)} items"
2826+
"Starting experiment '%s' run '%s' with %s items", name, run_name, len(data)
28082827
)
28092828

28102829
shared_fallback_experiment_id = self._create_observation_id()
@@ -2836,7 +2855,7 @@ async def process_item(item: ExperimentItem) -> ExperimentItemResult:
28362855
valid_results: List[ExperimentItemResult] = []
28372856
for i, result in enumerate(item_results):
28382857
if isinstance(result, Exception):
2839-
langfuse_logger.error(f"Item {i} failed: {result}")
2858+
langfuse_logger.error("Item %s failed: %s", i, result)
28402859
elif isinstance(result, ExperimentItemResult):
28412860
valid_results.append(result) # type: ignore
28422861

@@ -2849,7 +2868,7 @@ async def process_item(item: ExperimentItem) -> ExperimentItemResult:
28492868
)
28502869
run_evaluations.extend(evaluations)
28512870
except Exception as e:
2852-
langfuse_logger.error(f"Run evaluator failed: {e}")
2871+
langfuse_logger.error("Run evaluator failed: %s", e)
28532872

28542873
# Generate dataset run URL if applicable
28552874
dataset_run_id = next(
@@ -2894,7 +2913,7 @@ async def process_item(item: ExperimentItem) -> ExperimentItemResult:
28942913
)
28952914

28962915
except Exception as e:
2897-
langfuse_logger.error(f"Failed to store run evaluation: {e}")
2916+
langfuse_logger.error("Failed to store run evaluation: %s", e)
28982917

28992918
# Flush scores and traces
29002919
self.flush()
@@ -3016,7 +3035,7 @@ async def _process_experiment_item(
30163035

30173036
except Exception as e:
30183037
langfuse_logger.error(
3019-
f"Failed to create dataset run item: {e}"
3038+
"Failed to create dataset run item: %s", e
30203039
)
30213040

30223041
experiment_id = dataset_run_id or fallback_experiment_id
@@ -3115,7 +3134,7 @@ async def _process_experiment_item(
31153134
level="ERROR",
31163135
status_message=str(e),
31173136
)
3118-
langfuse_logger.error(f"Evaluator failed: {e}")
3137+
langfuse_logger.error("Evaluator failed: %s", e)
31193138
continue
31203139

31213140
evaluations.extend(eval_results)
@@ -3134,7 +3153,7 @@ async def _process_experiment_item(
31343153
)
31353154
except Exception as e:
31363155
langfuse_logger.error(
3137-
f"Failed to store evaluation: {e}"
3156+
"Failed to store evaluation: %s", e
31383157
)
31393158

31403159
if composite_evaluator and evaluations:
@@ -3182,7 +3201,7 @@ async def _process_experiment_item(
31823201
status_message=str(e),
31833202
)
31843203
langfuse_logger.error(
3185-
f"Composite evaluator failed: {e}"
3204+
"Composite evaluator failed: %s", e
31863205
)
31873206
composite_evals = []
31883207

@@ -3201,7 +3220,7 @@ async def _process_experiment_item(
32013220
)
32023221
except Exception as e:
32033222
langfuse_logger.error(
3204-
f"Failed to store composite evaluation: {e}"
3223+
"Failed to store composite evaluation: %s", e
32053224
)
32063225

32073226
evaluation_span.update(
@@ -3481,7 +3500,7 @@ def auth_check(self) -> bool:
34813500
try:
34823501
projects = self.api.projects.get()
34833502
langfuse_logger.debug(
3484-
f"Auth check successful, found {len(projects.data)} projects"
3503+
"Auth check successful, found %s projects", len(projects.data)
34853504
)
34863505
if len(projects.data) == 0:
34873506
raise Exception(
@@ -3491,7 +3510,7 @@ def auth_check(self) -> bool:
34913510

34923511
except AttributeError as e:
34933512
langfuse_logger.warning(
3494-
f"Auth check failed: Client not properly initialized. Error: {e}"
3513+
"Auth check failed: Client not properly initialized. Error: %s", e
34953514
)
34963515
return False
34973516

@@ -3521,7 +3540,7 @@ def create_dataset(
35213540
Dataset: The created dataset as returned by the Langfuse API.
35223541
"""
35233542
try:
3524-
langfuse_logger.debug(f"Creating datasets {name}")
3543+
langfuse_logger.debug("Creating datasets %s", name)
35253544

35263545
result = self.api.datasets.create(
35273546
name=name,
@@ -3582,7 +3601,7 @@ def create_dataset_item(
35823601
```
35833602
"""
35843603
try:
3585-
langfuse_logger.debug(f"Creating dataset item for dataset {dataset_name}")
3604+
langfuse_logger.debug("Creating dataset item for dataset %s", dataset_name)
35863605

35873606
# Media uploads must reference the (dataset, item) they belong to, and
35883607
# the item need not exist yet — so settle on the item id up front and
@@ -3757,7 +3776,8 @@ def _replace_json_path_value(
37573776
return json_path.set_value_at_path(value, path, replacement)
37583777
except Exception as e:
37593778
langfuse_logger.warning(
3760-
f"Failed to hydrate dataset media reference at JSONPath {path}",
3779+
"Failed to hydrate dataset media reference at JSONPath %s",
3780+
path,
37613781
exc_info=e,
37623782
)
37633783

@@ -3902,12 +3922,12 @@ def get_prompt(
39023922
max_retries, default_max_retries=2, max_retries_upper_bound=4
39033923
)
39043924

3905-
langfuse_logger.debug(f"Getting prompt '{cache_key}'")
3925+
langfuse_logger.debug("Getting prompt '%s'", cache_key)
39063926
cached_prompt = self._resources.prompt_cache.get(cache_key)
39073927

39083928
if cached_prompt is None or cache_ttl_seconds == 0:
39093929
langfuse_logger.debug(
3910-
f"Prompt '{cache_key}' not found in cache or caching disabled."
3930+
"Prompt '%s' not found in cache or caching disabled.", cache_key
39113931
)
39123932
try:
39133933
return self._fetch_prompt_and_update_cache(
@@ -3921,7 +3941,9 @@ def get_prompt(
39213941
except Exception as e:
39223942
if fallback:
39233943
langfuse_logger.warning(
3924-
f"Returning fallback prompt for '{cache_key}' due to fetch error: {e}"
3944+
"Returning fallback prompt for '%s' due to fetch error: %s",
3945+
cache_key,
3946+
e,
39253947
)
39263948

39273949
fallback_client_args: Dict[str, Any] = {
@@ -3949,10 +3971,12 @@ def get_prompt(
39493971
raise e
39503972

39513973
if cached_prompt.is_expired():
3952-
langfuse_logger.debug(f"Stale prompt '{cache_key}' found in cache.")
3974+
langfuse_logger.debug("Stale prompt '%s' found in cache.", cache_key)
39533975
try:
39543976
# refresh prompt in background thread, refresh_prompt deduplicates tasks
3955-
langfuse_logger.debug(f"Refreshing prompt '{cache_key}' in background.")
3977+
langfuse_logger.debug(
3978+
"Refreshing prompt '%s' in background.", cache_key
3979+
)
39563980

39573981
def refresh_task() -> None:
39583982
self._fetch_prompt_and_update_cache(
@@ -3970,14 +3994,17 @@ def refresh_task() -> None:
39703994
refresh_task,
39713995
)
39723996
langfuse_logger.debug(
3973-
f"Returning stale prompt '{cache_key}' from cache."
3997+
"Returning stale prompt '%s' from cache.", cache_key
39743998
)
39753999
# return stale prompt
39764000
return cached_prompt.value
39774001

39784002
except Exception as e:
39794003
langfuse_logger.warning(
3980-
f"Error when refreshing cached prompt '{cache_key}', returning cached version. Error: {e}"
4004+
"Error when refreshing cached prompt '%s', returning cached version. "
4005+
"Error: %s",
4006+
cache_key,
4007+
e,
39814008
)
39824009
# creation of refresh prompt task failed, return stale prompt
39834010
return cached_prompt.value
@@ -3995,7 +4022,7 @@ def _fetch_prompt_and_update_cache(
39954022
fetch_timeout_seconds: Optional[int],
39964023
) -> PromptClient:
39974024
cache_key = PromptCache.generate_cache_key(name, version=version, label=label)
3998-
langfuse_logger.debug(f"Fetching prompt '{cache_key}' from server...")
4025+
langfuse_logger.debug("Fetching prompt '%s' from server...", cache_key)
39994026

40004027
try:
40014028

@@ -4029,15 +4056,15 @@ def fetch_prompts() -> Any:
40294056

40304057
except NotFoundError as not_found_error:
40314058
langfuse_logger.warning(
4032-
f"Prompt '{cache_key}' not found during refresh, evicting from cache."
4059+
"Prompt '%s' not found during refresh, evicting from cache.", cache_key
40334060
)
40344061
if self._resources is not None:
40354062
self._resources.prompt_cache.delete(cache_key)
40364063
raise not_found_error
40374064

40384065
except Exception as e:
40394066
langfuse_logger.error(
4040-
f"Error while fetching prompt '{cache_key}': {str(e)}"
4067+
"Error while fetching prompt '%s': %s", cache_key, str(e)
40414068
)
40424069
raise e
40434070

@@ -4114,7 +4141,7 @@ def create_prompt(
41144141
ChatPromptClient: The prompt if type argument is 'chat'.
41154142
"""
41164143
try:
4117-
langfuse_logger.debug(f"Creating prompt {name=}, {labels=}")
4144+
langfuse_logger.debug("Creating prompt name=%r, labels=%r", name, labels)
41184145

41194146
if type == "chat":
41204147
if not isinstance(prompt, list):

‎langfuse/_client/get_client.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,9 @@ def get_client(*, public_key: Optional[str] = None) -> Langfuse:
142142
if target_instance is None:
143143
# No instance found with this key - client not initialized properly
144144
langfuse_logger.warning(
145-
f"No Langfuse client with public key {public_key} has been initialized. Skipping tracing for decorated function."
145+
"No Langfuse client with public key %s has been initialized. Skipping "
146+
"tracing for decorated function.",
147+
public_key,
146148
)
147149
return Langfuse(
148150
tracing_enabled=False, public_key="fake", secret_key="fake"

‎langfuse/_client/observe.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,9 @@ def sub_process():
187187
valid_types = set(get_observation_types_list(ObservationTypeLiteralNoEvent))
188188
if as_type is not None and as_type not in valid_types:
189189
logger.warning(
190-
f"Invalid as_type '{as_type}'. Valid types are: {', '.join(sorted(valid_types))}. Defaulting to 'span'."
190+
"Invalid as_type '%s'. Valid types are: %s. Defaulting to 'span'.",
191+
as_type,
192+
", ".join(sorted(valid_types)),
191193
)
192194
as_type = "span"
193195

0 commit comments

Comments
 (0)