@@ -51,6 +51,57 @@ def json_sink(message: Any) -> None: # noqa: ANN401
5151 sys .stdout .write (json .dumps (log_entry , ensure_ascii = False , separators = ("," , ":" )) + "\n " )
5252
5353
54+ def format_extra_fields (record : dict ) -> str :
55+ """Format extra fields as JSON string.
56+
57+ Parameters
58+ ----------
59+ record : dict
60+ The loguru record dictionary
61+
62+ Returns
63+ -------
64+ str
65+ JSON formatted extra fields or empty string
66+
67+ """
68+ if not record .get ("extra" ):
69+ return ""
70+
71+ # Filter out loguru's internal extra fields
72+ filtered_extra = {k : v for k , v in record ["extra" ].items () if not k .startswith ("_" ) and k not in ["name" ]}
73+
74+ # Handle nested extra structure - if there's an 'extra' key, use its contents
75+ if "extra" in filtered_extra and isinstance (filtered_extra ["extra" ], dict ):
76+ filtered_extra = filtered_extra ["extra" ]
77+
78+ if filtered_extra :
79+ extra_json = json .dumps (filtered_extra , ensure_ascii = False , separators = ("," , ":" ))
80+ return f" | { extra_json } "
81+
82+ return ""
83+
84+
85+ def extra_filter (record : dict ) -> dict :
86+ """Filter function to add extra fields to the message.
87+
88+ Parameters
89+ ----------
90+ record : dict
91+ The loguru record dictionary
92+
93+ Returns
94+ -------
95+ dict
96+ Modified record with extra fields appended to message
97+
98+ """
99+ extra_str = format_extra_fields (record )
100+ if extra_str :
101+ record ["message" ] = record ["message" ] + extra_str
102+ return record
103+
104+
54105class InterceptHandler (logging .Handler ):
55106 """Intercept standard library logging and redirect to loguru."""
56107
@@ -101,12 +152,16 @@ def configure_logging() -> None:
101152 )
102153 else :
103154 # Human-readable format for development
104- logger .add (
105- sys .stdout ,
106- format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
155+ logger_format = (
156+ "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
107157 "<level>{level: <8}</level> | "
108158 "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
109- "<level>{message}</level>" ,
159+ "{message}"
160+ )
161+ logger .add (
162+ sys .stderr ,
163+ format = logger_format ,
164+ filter = extra_filter ,
110165 level = log_level ,
111166 enqueue = True ,
112167 diagnose = True , # Include variable values in development
0 commit comments