Skip to content

Commit 1f40b5a

Browse files
committed
Add logging example in a controller
1 parent dbfa32d commit 1f40b5a

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

ProjectTemplates/ReferenceProject/Controllers/ProductsController.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using AutoMapper;
22
using Microsoft.AspNetCore.Http;
33
using Microsoft.AspNetCore.Mvc;
4-
using Microsoft.AspNetCore.Mvc.Formatters;
4+
using Microsoft.Extensions.Logging;
55
using ReferenceProject.Repo;
66
using System;
77
using System.Collections.Generic;
@@ -16,9 +16,11 @@ public class ProductsController: ControllerBase
1616
{
1717
Repo.IProductsRepo ProductsRepo { get; }
1818
IMapper Mapper { get; }
19+
ILogger<ProductsController> Logger { get; }
1920

20-
public ProductsController(Repo.IProductsRepo productsRepo, IMapper mapper)
21+
public ProductsController(IProductsRepo productsRepo, IMapper mapper, ILogger<ProductsController> logger)
2122
{
23+
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
2224
Mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
2325
ProductsRepo = productsRepo ?? throw new ArgumentNullException(nameof(productsRepo));
2426
}
@@ -61,7 +63,12 @@ public IActionResult Create(int id, [FromBody]Dto.UpdateProduct newProductDto)
6163
var newProduct = new Model.Product(id);
6264
Mapper.Map(newProductDto, newProduct);
6365
ProductsRepo.Create(newProduct);
64-
return Created($"{id}", Mapper.Map<Dto.Product>(ProductsRepo.GetById(id)));
66+
67+
var createdProduct = ProductsRepo.GetById(id);
68+
69+
Logger.LogInformation("New product was created: {@product}", createdProduct);
70+
71+
return Created($"{id}", Mapper.Map<Dto.Product>(createdProduct));
6572
}
6673

6774
/// <summary>

0 commit comments

Comments
 (0)