
ليه الـ string interpolation في ILogger غلط؟ شرح الـ message templates
- كاتب موثّق
- .NET 10
محتويات المقال
OrderId = 81723. مفيش ولا نتيجة، مع إن الـ payment service بتعمل log لكل خطوة. بحث في النص لقى السطر: "Payment declined for order 81723: card_declined". الكود اللي كتبه كان مستخدم $"..."، فمكان تخزين الـ logs استلم جملة جاهزة ومفيهاش أي field اسمه OrderId. والـ dashboard اللي المفروض يعدّ الـ declines حسب السبب عنده نفس المشكلة: مفيش field اسمه Reason يجمّع بيه، وكل رسالة نصها مختلف عن التانية.
الفكرة الغلط الشائعة
ILogger، ده نفس استخدام template فيه placeholders، بس أسهل في القراية. الاتنين بيطلّعوا نفس الرسالة، والـ interpolation كمان الـ compiler بيشيّك عليه.
string.Format ليه. وشكل الـ template، بالأقواس والـ arguments اللي بعده، شبه string.Format بأسماء، وده أسلوب ناس كتير اتعلموا يستبدلوه.
اللي بيحصل فعلًا
الـ template بيتنقل كـ نص ثابت ومعاه قيم ليها أسماء
LogWarning("Payment declined for order {OrderId}: {Reason}", orderId, reason) بيبعت الـ والقيم كل واحد لوحده. الـ logger بيحتفظ بيهم كـ key وقيمته: OrderId = 81723 و Reason = card_declined، ومعاهم الـ template نفسه تحت {OriginalFormat}. والنص مش بيتبني غير لما provider يطلبه. والـ provider اللي بيعمل ، زي OpenTelemetry أو Application Insights، يقدر يخزّن كل قيمة كـ field. وبالـ JSON console formatter، تجربة على .NET 10 طبعت ده (بعد ما شلنا الأجزاء اللي مش مهمة هنا):
{ "Message": "Payment declined for order 81723: card_declined", "State": { "OrderId": 81723, "Reason": "card_declined", "{OriginalFormat}": "Payment declined for order {OrderId}: {Reason}" }}الـ interpolation بيعمل format قبل ما الـ logger يشوف أي حاجة
$"Payment declined for order {orderId}: {reason}" لـ string جاهز قبل ما LogWarning يشتغل. فالـ logger بيستلم "template" مفيهوش placeholders ولا قيم. وفي نفس التجربة، الـ state كان فيه حاجة واحدة بس: {OriginalFormat}، وجواه الجملة كلها. مفيش حاجة تعمل بيها filter، ولأن الـ template بيختلف مع كل أوردر، مفيش حاجة تجمّع بيها كمان. وده بالظبط اللي الـ CA2254 بينبّه عليه: الربط بين أسماء الـ placeholders وقيمها بيضيع.
القيم بتقابل الـ placeholders بالترتيب، مش بالاسم
Log{Level}، الأسماء اللي في الـ template مش بتتربط بالمتغيرات بتاعتك، اللي بيربطها هو ترتيب الـ arguments. اكتب "... {OrderId}: {Reason}", reason, orderId وهتلاقي التجربة سجّلت OrderId = card_declined من غير أي warning. والـ docs بتقولها صريحة: الـ placeholders بتمشي بالترتيب. أما الـ source generator فمختلف: بيطابق الـ placeholders بأسماء الـ parameters من غير ما يفرق بين الـ capital والـ small، ولو فيه placeholder في الـ template ملوش parameter، ده build error (SYSLIB1014).
التكلفة لما الـ level يبقى مقفول
LogDebug($"... {cart}") كان بينادي ToString بتاع الـ cart كل مرة. نسخة الـ template عمرها ما عملت format لحاجة، بس برضه عملت allocate لـ 64 byte في كل call عشان الـ array بتاعة الـ arguments والـ int اللي اتعمله boxing. أما الـ method اللي متعلّم بـ [LoggerMessage] فماعملش allocate لأي حاجة: الكود المتولّد بيشيّك على IsEnabled الأول، وبياخد parameters ليها types محددة، فالـ value types مش بتتعمل boxing.
الـ payment log بعد الـ fix
public sealed class PaymentService(ILogger<PaymentService> logger){ public void OnDeclined(int orderId, string reason, Cart cart) { // Built before the call: no OrderId field, a new text per order logger.LogWarning($"Payment declined for order {orderId}: {reason}"); // Calls cart.ToString() even when Debug is off logger.LogDebug($"Cart at decline: {cart}"); }}public sealed partial class PaymentService(ILogger<PaymentService> logger){ public void OnDeclined(int orderId, string reason, Cart cart) { LogDeclined(orderId, reason); LogCart(cart); // checks IsEnabled(Debug) before any work } // The generator writes the bodies, using the logger parameter above [LoggerMessage(Level = LogLevel.Warning, Message = "Payment declined for order {OrderId}: {Reason}")] partial void LogDeclined(int orderId, string reason); [LoggerMessage(Level = LogLevel.Debug, Message = "Cart at decline: {Cart}")] partial void LogCart(Cart cart);}[LoggerMessage] method اللي مش static تقدر تاخد الـ logger من parameter في الـ primary constructor، وده اللي النسخة الصح معتمدة عليه. والـ template العادي، logger.LogWarning("Payment declined for order {OrderId}: {Reason}", orderId, reason)، لوحده بيصلّح مشكلة الـ fields الناقصة، والـ generator بيزوّد الطريق اللي من غير allocations والـ checks وقت الـ compile.
تلات طرق تكتب بيها نفس السطر
$"... {orderId}" | "... {OrderId}", orderId | [LoggerMessage] | |
|---|---|---|---|
OrderId و Reason | OrderId و Reason | ||
{OriginalFormat} | |||
ToString | IsEnabled الأول | ||
تطبقها إزاي في مشروعك
لاقي الـ calls اللي فيها interpolation خلّي الـ CA2254 بـ warning واعمل build، أو دوّر على أي Logcall بعدها($". كل واحدة منهم log entry من غير fields.سمّي الـ placeholders باللي جواها استخدم أسماء PascalCase زي الـ fields اللي هتدوّر بيها، زي {OrderId}و{UserId}، وخلّي نفس القيمة ليها نفس الاسم في الكود كله، عشان filter واحد يلاقي كل الـ entries.ابعت الـ exceptions كـ exceptions اكتب logger.LogError(ex, "Payment failed for order {OrderId}", orderId)، مش$"... {ex.Message}". الـ parameter بتاع الـ exception بيحتفظ بالـ type والـ stack trace، والرسالة اللي فيها interpolation بتحتفظ بسطر نص واحد.ولّد الكود للأماكن اللي بتتنادى كتير للـ log calls اللي جوه loops، والـ middleware اللي بيشتغل مع كل request، وأي حاجة على Debug أو Trace، اعمل methods بـ [LoggerMessage]في class متعلّمةpartialونادي عليها هي.
الخلاصة
الـ message template بيوصل للـ logger كـ نص ثابت ومعاه قيم ليها أسماء، والـ interpolated string بيوصل نص جاهز. الـ templates بس هي اللي بتدّي أماكن تخزين الـ logs fields تعمل بيها filter وتجمّع وتعدّ، و {OriginalFormat}ثابت لكل event.مع methods الـ Log{Level}القيم بتقابل الـ placeholders بالترتيب، والـ source generator بيطابقها بالاسم وبيشيّك وقت الـ compile.الـ interpolation بيعمل format حتى والـ level مقفول، والـ [LoggerMessage]بيشيّك علىIsEnabledالأول ومش بيعمل boxing، بس ولا واحد فيهم بيوفّر عليك حساب الـ arguments.
التعليقات (0)