$context Optional context. */ public static function log( int $job_id, string $level, string $message, array $context = array() ): void { global $wpdb; $table = $wpdb->prefix . 'brverify_logs'; $now = current_time( 'mysql' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->insert( $table, array( 'job_id' => $job_id, 'level' => sanitize_key( $level ), 'message' => self::truncate( $message, 65000 ), 'context_json' => $context ? wp_json_encode( $context ) : null, 'created_at' => $now, ), array( '%d', '%s', '%s', '%s', '%s' ) ); } /** * Convenience helpers. * * @param int $job_id Job id. * @param string $message Message. * @param array $context Context. */ public static function info( int $job_id, string $message, array $context = array() ): void { self::log( $job_id, 'info', $message, $context ); } /** * @param int $job_id Job id. * @param string $message Message. * @param array $context Context. */ public static function warning( int $job_id, string $message, array $context = array() ): void { self::log( $job_id, 'warning', $message, $context ); } /** * @param int $job_id Job id. * @param string $message Message. * @param array $context Context. */ public static function error( int $job_id, string $message, array $context = array() ): void { self::log( $job_id, 'error', $message, $context ); } /** * Recent log lines for a job. * * @param int $job_id Job id. * @param int $limit Max rows. * @return list> */ public static function recent( int $job_id, int $limit = 50 ): array { global $wpdb; $table = $wpdb->prefix . 'brverify_logs'; $limit = max( 1, min( 200, $limit ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT id, level, message, context_json, created_at FROM %i WHERE job_id = %d ORDER BY id DESC LIMIT %d', $table, $job_id, $limit ), ARRAY_A ); return is_array( $rows ) ? array_reverse( $rows ) : array(); } /** * Truncate long strings. * * @param string $text Text. * @param int $maxlen Max length. */ private static function truncate( string $text, int $maxlen ): string { if ( strlen( $text ) <= $maxlen ) { return $text; } return substr( $text, 0, $maxlen - 3 ) . '...'; } }