@@ -295,11 +295,23 @@ private function write_log( $level, $message, array $context = array() ) {
295
295
return ;
296
296
}
297
297
298
+ // Ensure the origin is present in the context so we know which function/method produced the log.
299
+ $ merged_context = array_merge ( $ this ->context , $ context );
300
+ if ( ! isset ( $ merged_context ['function ' ] ) || ! isset ( $ merged_context ['line ' ] ) ) {
301
+ $ origin = $ this ->get_calling_origin ();
302
+ if ( ! isset ( $ merged_context ['function ' ] ) ) {
303
+ $ merged_context ['function ' ] = is_array ( $ origin ) && isset ( $ origin ['function ' ] ) ? $ origin ['function ' ] : (string ) $ origin ;
304
+ }
305
+ if ( ! isset ( $ merged_context ['line ' ] ) && is_array ( $ origin ) && isset ( $ origin ['line ' ] ) ) {
306
+ $ merged_context ['line ' ] = $ origin ['line ' ];
307
+ }
308
+ }
309
+
298
310
$ record = array (
299
311
'timestamp ' => gmdate ( 'c ' ),
300
312
'level ' => isset ( self ::$ levels [ $ level ] ) ? self ::$ levels [ $ level ] : 'UNKNOWN ' ,
301
313
'message ' => $ message ,
302
- 'context ' => array_merge ( $ this -> context , $ context ) ,
314
+ 'context ' => $ merged_context ,
303
315
);
304
316
305
317
if ( wp_doing_ajax () ) {
@@ -322,6 +334,39 @@ private function write_log( $level, $message, array $context = array() ) {
322
334
error_log ( $ formatted , 3 , $ this ->filepath );
323
335
}
324
336
337
+ /**
338
+ * Determine the caller origin (Class::method() or function()) for the current log entry,
339
+ * returning both the function signature and source line number.
340
+ *
341
+ * @since 5.1.0
342
+ * @return array{function:string,line:int|null}
343
+ */
344
+ private function get_calling_origin () {
345
+ // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
346
+ $ trace = debug_backtrace ( DEBUG_BACKTRACE_IGNORE_ARGS , 10 );
347
+ foreach ( $ trace as $ frame ) {
348
+ // Skip frames from this logger class.
349
+ if ( isset ( $ frame ['class ' ] ) && __CLASS__ === $ frame ['class ' ] ) {
350
+ continue ;
351
+ }
352
+ if ( isset ( $ frame ['function ' ] ) ) {
353
+ $ func = isset ( $ frame ['class ' ] )
354
+ ? ( $ frame ['class ' ] . ( isset ( $ frame ['type ' ] ) ? $ frame ['type ' ] : ':: ' ) . $ frame ['function ' ] . '() ' )
355
+ : ( $ frame ['function ' ] . '() ' );
356
+ $ line = isset ( $ frame ['line ' ] ) ? (int ) $ frame ['line ' ] : null ;
357
+
358
+ return array (
359
+ 'function ' => $ func ,
360
+ 'line ' => $ line ,
361
+ );
362
+ }
363
+ }
364
+ return array (
365
+ 'function ' => 'unknown ' ,
366
+ 'line ' => null ,
367
+ );
368
+ }
369
+
325
370
/**
326
371
* Log a debug message.
327
372
*
0 commit comments