Start learning free

LESSON 141 OF 173 · BACKEND: TESTS AND RUNNING IT

Logging in C#

Practice

On a server nobody watches the screen, so Console.WriteLine is no help there. Instead the shop writes a log: lines that are kept, so you can read them later, for example when a customer says their order went wrong. In ASP.NET Core, app.Logger writes those lines, and each one gets a level: Information for things that went as planned, Warning for something unusual.

You give app.Logger.LogInformation a message with placeholders in braces, then the values: each value fills the next placeholder, in order. In a sign-up route, for example:

app.Logger.LogInformation("New user: {Name}, age {Age}", name, age);

With name "Ana" and age 30, the log gets the message New user: Ana, age 30. This lesson's check shows each line as its level, a colon and the message: Information: New user: Ana, age 30.

Test the log too, because a log line can break without anyone noticing. This lesson gives you AssertLogs(LogLevel.Information): keep it in logs, and every line logged at Information or above inside a using (logs) { … } block is caught. At the block's }, the test fails if none was. After the block, logs.Output is the list of the caught lines, each written like the one above.

The check places three orders and shows what your shop logged for each:

POST /orders {"product_id": 1, "quantity": 2}  →  201
  log: Information: Order placed: 2 x Mug, total 24
POST /orders {"product_id": 6, "quantity": 3}  →  201
  log: Information: Order placed: 3 x Teapot, total 66
POST /orders {"product_id": 99, "quantity": 1}  →  404
  log: Warning: Order for unknown product 99

Your task: log every placed order with app.Logger.LogInformation and every order for an unknown product with app.Logger.LogWarning. Then write the test "order is logged", which posts 2 Mugs inside a using (logs) block and checks that logs.Output holds exactly the expected line. The check runs it on the shop, where it must pass, and on two broken copies, one that logs nothing and one that logs the price instead of the total, where it must fail.


Assignment
Follow the Coding Tutorial to log the orders with LogInformation and LogWarning, and to write a test that reads the log with AssertLogs.


Hint
Put each log line right before its return, where everything it needs is known. Each line in logs.Output is the level, a colon, a space and the message: "Information: …".


STEP 1 OF 7
    Ctrl + Enter to check

    Log Basics in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free