🔇 🔊 Fix #57 - Implement logging, using DI #64

Merged
alexis.drai merged 1 commits from implement-logging into master 2 years ago

@ -44,5 +44,5 @@ jobs:
run: | run: |
.\.sonar\scanner\dotnet-sonarscanner begin /k:"draialexis_cat_cafe" /o:"draialexis" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.vscoveragexml.reportsPaths=coverage.xml .\.sonar\scanner\dotnet-sonarscanner begin /k:"draialexis_cat_cafe" /o:"draialexis" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.vscoveragexml.reportsPaths=coverage.xml
dotnet build cat_cafe\cat_cafe.sln dotnet build cat_cafe\cat_cafe.sln
.\.sonar\scanner\dotnet-coverage collect "dotnet test" -f xml -o "coverage.xml" dotnet test cat_cafe\cat_cafe.Tests\cat_cafe.Tests.csproj /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=./coverage.xml
.\.sonar\scanner\dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}" .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}"

@ -27,27 +27,47 @@ namespace cat_cafe.Controllers
[HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<BarDto>>> GetBars() public async Task<ActionResult<IEnumerable<BarDto>>> GetBars()
{ {
var bars = await _context.Bars try
.Include(b => b.Cats) {
.ToListAsync(); var bars = await _context.Bars
.Include(b => b.Cats)
.ToListAsync();
_logger.LogInformation("Bars retrieved successfully.");
return Ok(_mapper.Map<IEnumerable<BarDto>>(bars));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve all bars.");
return BadRequest(ex);
}
return Ok(_mapper.Map<IEnumerable<BarDto>>(bars));
} }
// GET: api/v1/Bars/5 // GET: api/v1/Bars/5
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<BarDto>> GetBar(long id) public async Task<ActionResult<BarDto>> GetBar(long id)
{ {
var bar = await _context.Bars try
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
{ {
return NotFound(); var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
{
_logger.LogError("No such bar.");
return NotFound();
}
_logger.LogInformation("Bar retrieved successfully.");
return Ok(_mapper.Map<BarDto>(bar));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve bar.");
return BadRequest(ex);
} }
return Ok(_mapper.Map<BarDto>(bar));
} }
// PUT: api/v1/Bars/5 // PUT: api/v1/Bars/5
@ -55,27 +75,39 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutBar(long id, BarDto barDto) public async Task<IActionResult> PutBar(long id, BarDto barDto)
{ {
if (id != barDto.Id) try
{ {
return BadRequest(); if (id != barDto.Id)
{
_logger.LogError("No such bar.");
return BadRequest();
}
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
{
_logger.LogInformation("Bar not found.");
return NotFound();
}
_mapper.Map(barDto, bar);
bar.Cats = await _context.Cats
.Where(c => barDto.CatIds.Contains(c.Id))
.ToListAsync();
await _context.SaveChangesAsync();
_logger.LogInformation("Bar updated successfully.");
return NoContent();
} }
catch (Exception ex)
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
{ {
return NotFound(); _logger.LogError(ex, "Failed to update bar.");
return BadRequest(ex);
} }
_mapper.Map(barDto, bar);
bar.Cats = await _context.Cats
.Where(c => barDto.CatIds.Contains(c.Id))
.ToListAsync();
await _context.SaveChangesAsync();
return NoContent();
} }
// POST: api/v1/Bars // POST: api/v1/Bars
@ -83,34 +115,50 @@ namespace cat_cafe.Controllers
[HttpPost] [HttpPost]
public async Task<ActionResult<BarDto>> CreateBar(BarDto barDto) public async Task<ActionResult<BarDto>> CreateBar(BarDto barDto)
{ {
var bar = _mapper.Map<Bar>(barDto); try
bar.Cats = await _context.Cats {
.Where(c => barDto.CatIds.Contains(c.Id)) var bar = _mapper.Map<Bar>(barDto);
.ToListAsync(); bar.Cats = await _context.Cats
.Where(c => barDto.CatIds.Contains(c.Id))
_context.Bars.Add(bar); .ToListAsync();
await _context.SaveChangesAsync();
_context.Bars.Add(bar);
await _context.SaveChangesAsync();
_logger.LogInformation("Bar created succesfully.");
return CreatedAtAction(nameof(GetBar), new { id = bar.Id }, _mapper.Map<BarDto>(bar));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create bar.");
return BadRequest(ex);
}
return CreatedAtAction(nameof(GetBar), new { id = bar.Id }, _mapper.Map<BarDto>(bar));
} }
// DELETE: api/v1/Bars/5 // DELETE: api/v1/Bars/5
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteBar(long id) public async Task<IActionResult> DeleteBar(long id)
{ {
var bar = await _context.Bars try
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
{ {
return NotFound(); var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar != null)
{
_context.Bars.Remove(bar);
await _context.SaveChangesAsync();
_logger.LogInformation("Bar deleted succesfully.");
}
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete bar.");
return BadRequest(ex);
} }
_context.Bars.Remove(bar);
await _context.SaveChangesAsync();
return NoContent();
} }
} }
} }

@ -38,9 +38,18 @@ namespace cat_cafe.Controllers
public async Task<ActionResult<IEnumerable<CatDto>>> GetCats() public async Task<ActionResult<IEnumerable<CatDto>>> GetCats()
{ {
var cats = await _context.Cats.ToListAsync(); try
cats.Add(new Cat { Id = -1, Age = 42, Name = "Hi! I'm the secret V1 cat" }); {
return Ok(_mapper.Map<List<CatDto>>(cats)); var cats = await _context.Cats.ToListAsync();
cats.Add(new Cat { Id = -1, Age = 42, Name = "Hi! I'm the secret V1 cat" });
_logger.LogInformation("Cats retrieved successfully.");
return Ok(_mapper.Map<List<CatDto>>(cats));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve all cats.");
return BadRequest(ex);
}
} }
@ -50,23 +59,41 @@ namespace cat_cafe.Controllers
public async Task<ActionResult<IEnumerable<CatDto>>> GetCatsV2() public async Task<ActionResult<IEnumerable<CatDto>>> GetCatsV2()
{ {
var cats = await _context.Cats.ToListAsync(); try
{
var cats = await _context.Cats.ToListAsync();
return Ok(_mapper.Map<List<CatDto>>(cats)); _logger.LogInformation("Cats retrieved successfully.");
return Ok(_mapper.Map<List<CatDto>>(cats));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve all cats.");
return BadRequest(ex);
}
} }
// GET: api/v1/Cats/5 // GET: api/v1/Cats/5
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<CatDto>> GetCat(long id) public async Task<ActionResult<CatDto>> GetCat(long id)
{ {
var cat = await _context.Cats.FindAsync(id); try
if (cat == null)
{ {
return NotFound(); var cat = await _context.Cats.FindAsync(id);
if (cat == null)
{
_logger.LogInformation("Cat not found.");
return NotFound();
}
_logger.LogInformation("Cat retrieved successfully.");
return Ok(_mapper.Map<CatDto>(cat));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve cat.");
return BadRequest(ex);
} }
return Ok(_mapper.Map<CatDto>(cat));
} }
// PUT: api/v1/Cats/5 // PUT: api/v1/Cats/5
@ -74,24 +101,36 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutCat(long id, CatDto catDto) public async Task<IActionResult> PutCat(long id, CatDto catDto)
{ {
if (id != catDto.Id) try
{ {
return BadRequest(); if (id != catDto.Id)
} {
_logger.LogError("No such cat.");
return BadRequest();
}
var cat = await _context.Cats var cat = await _context.Cats
.SingleOrDefaultAsync(c => c.Id == id); .SingleOrDefaultAsync(c => c.Id == id);
if (cat == null) if (cat == null)
{ {
return NotFound(); _logger.LogInformation("Cat not found.");
} return NotFound();
}
_mapper.Map(catDto, cat);
_mapper.Map(catDto, cat); await _context.SaveChangesAsync();
await _context.SaveChangesAsync(); _logger.LogInformation("Cat updated successfully.");
return NoContent();
}
return NoContent(); catch (Exception ex)
{
_logger.LogError(ex, "Failed to update cat.");
return BadRequest(ex);
}
} }
// POST: api/v1/Cats // POST: api/v1/Cats
@ -99,29 +138,45 @@ namespace cat_cafe.Controllers
[HttpPost] [HttpPost]
public async Task<ActionResult<CatDto>> PostCat(CatDto catDto) public async Task<ActionResult<CatDto>> PostCat(CatDto catDto)
{ {
Cat cat = _mapper.Map<Cat>(catDto); try
_context.Cats.Add(cat); {
await _context.SaveChangesAsync(); Cat cat = _mapper.Map<Cat>(catDto);
_context.Cats.Add(cat);
await _context.SaveChangesAsync();
await _webSocketHandler.BroadcastMessageAsync("entity-created"); await _webSocketHandler.BroadcastMessageAsync("entity-created");
_logger.LogInformation("Cat created successfully.");
return CreatedAtAction("GetCat", new { id = catDto.Id }, _mapper.Map<CatDto>(cat));
return CreatedAtAction("GetCat", new { id = catDto.Id }, _mapper.Map<CatDto>(cat)); }
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create cat.");
return BadRequest(ex);
}
} }
// DELETE: api/v1/Cats/5 // DELETE: api/v1/Cats/5
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteCat(long id) public async Task<IActionResult> DeleteCat(long id)
{ {
var cat = await _context.Cats.FindAsync(id); try
if (cat == null)
{ {
return NotFound(); var cat = await _context.Cats.FindAsync(id);
if (cat != null)
{
_context.Cats.Remove(cat);
await _context.SaveChangesAsync();
_logger.LogInformation("Cat deleted successfully.");
}
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete cat.");
return BadRequest(ex);
} }
_context.Cats.Remove(cat);
await _context.SaveChangesAsync();
return NoContent();
} }
} }
} }

@ -29,35 +29,42 @@ namespace cat_cafe.Controllers
[HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<CustomerDto>>> GetCustomers() public async Task<ActionResult<IEnumerable<CustomerDto>>> GetCustomers()
{ {
Log.Information(this.Request.Method + " => get All customers"); try
{
var customers = await _context.Customers.ToListAsync(); var customers = await _context.Customers.ToListAsync();
_logger.LogInformation("Customers retrieved successfully.");
Log.Information(this.Request.Method + " => " return Ok(_mapper.Map<List<CustomerDto>>(customers));
+ this.Response.StatusCode.ToString() + " " }
+ customers.GetType().ToString() + " length[" catch (Exception ex)
+ customers.Count + "]"); {
return Ok(_mapper.Map<List<CustomerDto>>(customers)); _logger.LogError(ex, "Failed to retrieve customers.");
return BadRequest(ex);
}
} }
// GET: api/v1/Customers/5 // GET: api/v1/Customers/5
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<CustomerDto>> GetCustomer(long id) public async Task<ActionResult<CustomerDto>> GetCustomer(long id)
{ {
Log.Information(this.Request.Method + " => get by ID {@id}", id); try
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{ {
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{
_logger.LogInformation("Customer not found.");
return NotFound();
}
Log.Information(this.Request.Method + " => " + NotFound().StatusCode.ToString()); _logger.LogInformation("Customer retrieved successfully.");
return NotFound(); return Ok(_mapper.Map<CustomerDto>(customer));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve customer.");
return BadRequest(ex);
} }
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customer.GetType().ToString() + " "
+ JsonConvert.SerializeObject(customer).ToString());
return Ok(_mapper.Map<CustomerDto>(customer));
} }
// PUT: api/v1/Customers/5 // PUT: api/v1/Customers/5
@ -65,26 +72,36 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutCustomer(long id, CustomerDto customerDto) public async Task<IActionResult> PutCustomer(long id, CustomerDto customerDto)
{ {
Log.Information(this.Request.Method + " => put by ID {@id}", id); try
if (id != customerDto.Id)
{ {
Log.Information(this.Request.Method + " => " + BadRequest().StatusCode.ToString() + " IDs not matching"); if (id != customerDto.Id)
return BadRequest(); {
} _logger.LogError("No such customer.");
return BadRequest();
}
var customer = await _context.Customers var customer = await _context.Customers
.SingleOrDefaultAsync(c => c.Id == id); .SingleOrDefaultAsync(c => c.Id == id);
if (customer == null) if (customer == null)
{ {
return NotFound(); _logger.LogInformation("Customer not found.");
} return NotFound();
}
_mapper.Map(customerDto, customer); _mapper.Map(customerDto, customer);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
return NoContent(); _logger.LogInformation("Customer updated successfully.");
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update customer.");
return BadRequest(ex);
}
} }
// POST: api/v1/Customers // POST: api/v1/Customers
@ -92,42 +109,44 @@ namespace cat_cafe.Controllers
[HttpPost] [HttpPost]
public async Task<ActionResult<CustomerDto>> PostCustomer(CustomerDto customerDto) public async Task<ActionResult<CustomerDto>> PostCustomer(CustomerDto customerDto)
{ {
Log.Information(this.Request.Method + " => post customer"); try
{
Customer customer = _mapper.Map<Customer>(customerDto); Customer customer = _mapper.Map<Customer>(customerDto);
_context.Customers.Add(customer); _context.Customers.Add(customer);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
Log.Information(this.Request.Method + " => " _logger.LogInformation("Customer created successfully.");
+ 201 + " " return CreatedAtAction("GetCustomer", new { id = customer.Id }, _mapper.Map<CustomerDto>(customer));
+ customer.GetType().ToString() + " " }
+ JsonConvert.SerializeObject(customer).ToString()); catch (Exception ex)
{
_logger.LogError(ex, "Failed to create customer.");
return BadRequest(ex);
}
return CreatedAtAction("GetCustomer", new { id = customer.Id }, _mapper.Map<CustomerDto>(customer));
} }
// DELETE: api/v1/Customers/5 // DELETE: api/v1/Customers/5
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteCustomer(long id) public async Task<IActionResult> DeleteCustomer(long id)
{ {
Log.Information(this.Request.Method + " => delete by ID {@id}", id); try
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{ {
Log.Information(this.Request.Method + " => " + NotFound().StatusCode.ToString()); var customer = await _context.Customers.FindAsync(id);
return NotFound(); if (customer != null)
{
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
_logger.LogInformation("Customer deleted successfully.");
}
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete customer.");
return BadRequest(ex);
} }
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customer.GetType().ToString() + " "
+ JsonConvert.SerializeObject(customer).ToString());
return Ok();
} }
} }
} }

@ -3,6 +3,7 @@ using cat_cafe.WeSo;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Serilog; using Serilog;
using System.Net.WebSockets; using System.Net.WebSockets;
using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -10,6 +11,7 @@ List<WebSocket> _sockets = new();
// Add services to the container. // Add services to the container.
builder.Services.AddLogging(configure => configure.AddFile("log.txt"));
builder.Services.AddSingleton<List<WebSocket>>(x => _sockets); builder.Services.AddSingleton<List<WebSocket>>(x => _sockets);
builder.Services.AddSingleton<WebSocketHandler>(); builder.Services.AddSingleton<WebSocketHandler>();
builder.Services.AddControllers(); builder.Services.AddControllers();
@ -87,6 +89,4 @@ app.Use(async (context, next) =>
} }
}); });
Log.Information("program start");
app.Run(); app.Run();

Loading…
Cancel
Save