🔇 🔊 Fix #57 - Implement logging, using DI
continuous-integration/drone/push Build is passing Details

pull/64/head
Alexis Drai 2 years ago
parent 58ef86466c
commit 966f4591ea

@ -44,5 +44,5 @@ jobs:
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
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 }}"

@ -27,27 +27,47 @@ namespace cat_cafe.Controllers
[HttpGet]
public async Task<ActionResult<IEnumerable<BarDto>>> GetBars()
{
var bars = await _context.Bars
.Include(b => b.Cats)
.ToListAsync();
try
{
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
[HttpGet("{id}")]
public async Task<ActionResult<BarDto>> GetBar(long id)
{
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
try
{
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
@ -55,27 +75,39 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")]
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();
}
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
catch (Exception ex)
{
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
@ -83,34 +115,50 @@ namespace cat_cafe.Controllers
[HttpPost]
public async Task<ActionResult<BarDto>> CreateBar(BarDto barDto)
{
var bar = _mapper.Map<Bar>(barDto);
bar.Cats = await _context.Cats
.Where(c => barDto.CatIds.Contains(c.Id))
.ToListAsync();
_context.Bars.Add(bar);
await _context.SaveChangesAsync();
try
{
var bar = _mapper.Map<Bar>(barDto);
bar.Cats = await _context.Cats
.Where(c => barDto.CatIds.Contains(c.Id))
.ToListAsync();
_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
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBar(long id)
{
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
try
{
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()
{
var cats = await _context.Cats.ToListAsync();
cats.Add(new Cat { Id = -1, Age = 42, Name = "Hi! I'm the secret V1 cat" });
return Ok(_mapper.Map<List<CatDto>>(cats));
try
{
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()
{
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
[HttpGet("{id}")]
public async Task<ActionResult<CatDto>> GetCat(long id)
{
var cat = await _context.Cats.FindAsync(id);
if (cat == null)
try
{
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
@ -74,24 +101,36 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")]
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
.SingleOrDefaultAsync(c => c.Id == id);
var cat = await _context.Cats
.SingleOrDefaultAsync(c => c.Id == id);
if (cat == null)
{
return NotFound();
}
if (cat == null)
{
_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
@ -99,29 +138,45 @@ namespace cat_cafe.Controllers
[HttpPost]
public async Task<ActionResult<CatDto>> PostCat(CatDto catDto)
{
Cat cat = _mapper.Map<Cat>(catDto);
_context.Cats.Add(cat);
await _context.SaveChangesAsync();
try
{
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
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCat(long id)
{
var cat = await _context.Cats.FindAsync(id);
if (cat == null)
try
{
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]
public async Task<ActionResult<IEnumerable<CustomerDto>>> GetCustomers()
{
Log.Information(this.Request.Method + " => get All customers");
var customers = await _context.Customers.ToListAsync();
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customers.GetType().ToString() + " length["
+ customers.Count + "]");
return Ok(_mapper.Map<List<CustomerDto>>(customers));
try
{
var customers = await _context.Customers.ToListAsync();
_logger.LogInformation("Customers retrieved successfully.");
return Ok(_mapper.Map<List<CustomerDto>>(customers));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve customers.");
return BadRequest(ex);
}
}
// GET: api/v1/Customers/5
[HttpGet("{id}")]
public async Task<ActionResult<CustomerDto>> GetCustomer(long id)
{
Log.Information(this.Request.Method + " => get by ID {@id}", id);
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
try
{
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());
return NotFound();
_logger.LogInformation("Customer retrieved successfully.");
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
@ -65,26 +72,36 @@ namespace cat_cafe.Controllers
[HttpPut("{id}")]
public async Task<IActionResult> PutCustomer(long id, CustomerDto customerDto)
{
Log.Information(this.Request.Method + " => put by ID {@id}", id);
if (id != customerDto.Id)
try
{
Log.Information(this.Request.Method + " => " + BadRequest().StatusCode.ToString() + " IDs not matching");
return BadRequest();
}
if (id != customerDto.Id)
{
_logger.LogError("No such customer.");
return BadRequest();
}
var customer = await _context.Customers
.SingleOrDefaultAsync(c => c.Id == id);
var customer = await _context.Customers
.SingleOrDefaultAsync(c => c.Id == id);
if (customer == null)
{
return NotFound();
}
if (customer == null)
{
_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
@ -92,42 +109,44 @@ namespace cat_cafe.Controllers
[HttpPost]
public async Task<ActionResult<CustomerDto>> PostCustomer(CustomerDto customerDto)
{
Log.Information(this.Request.Method + " => post customer");
Customer customer = _mapper.Map<Customer>(customerDto);
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
try
{
Customer customer = _mapper.Map<Customer>(customerDto);
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
Log.Information(this.Request.Method + " => "
+ 201 + " "
+ customer.GetType().ToString() + " "
+ JsonConvert.SerializeObject(customer).ToString());
_logger.LogInformation("Customer created successfully.");
return CreatedAtAction("GetCustomer", new { id = customer.Id }, _mapper.Map<CustomerDto>(customer));
}
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
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCustomer(long id)
{
Log.Information(this.Request.Method + " => delete by ID {@id}", id);
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
try
{
Log.Information(this.Request.Method + " => " + NotFound().StatusCode.ToString());
return NotFound();
var customer = await _context.Customers.FindAsync(id);
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 Serilog;
using System.Net.WebSockets;
using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
@ -10,6 +11,7 @@ List<WebSocket> _sockets = new();
// Add services to the container.
builder.Services.AddLogging(configure => configure.AddFile("log.txt"));
builder.Services.AddSingleton<List<WebSocket>>(x => _sockets);
builder.Services.AddSingleton<WebSocketHandler>();
builder.Services.AddControllers();
@ -87,6 +89,4 @@ app.Use(async (context, next) =>
}
});
Log.Information("program start");
app.Run();

Loading…
Cancel
Save