🔇 🔊 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 }}"

@ -26,17 +26,28 @@ namespace cat_cafe.Controllers
// GET: api/v1/Bars
[HttpGet]
public async Task<ActionResult<IEnumerable<BarDto>>> GetBars()
{
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);
}
}
// GET: api/v1/Bars/5
[HttpGet("{id}")]
public async Task<ActionResult<BarDto>> GetBar(long id)
{
try
{
var bar = await _context.Bars
.Include(b => b.Cats)
@ -44,19 +55,31 @@ namespace cat_cafe.Controllers
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);
}
}
// PUT: api/v1/Bars/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutBar(long id, BarDto barDto)
{
try
{
if (id != barDto.Id)
{
_logger.LogError("No such bar.");
return BadRequest();
}
@ -66,6 +89,7 @@ namespace cat_cafe.Controllers
if (bar == null)
{
_logger.LogInformation("Bar not found.");
return NotFound();
}
@ -75,13 +99,23 @@ namespace cat_cafe.Controllers
.ToListAsync();
await _context.SaveChangesAsync();
_logger.LogInformation("Bar updated successfully.");
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update bar.");
return BadRequest(ex);
}
}
// POST: api/v1/Bars
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<BarDto>> CreateBar(BarDto barDto)
{
try
{
var bar = _mapper.Map<Bar>(barDto);
bar.Cats = await _context.Cats
@ -90,27 +124,41 @@ namespace cat_cafe.Controllers
_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);
}
}
// DELETE: api/v1/Bars/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBar(long id)
{
try
{
var bar = await _context.Bars
.Include(b => b.Cats)
.SingleOrDefaultAsync(b => b.Id == id);
if (bar == null)
if (bar != null)
{
return NotFound();
}
_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);
}
}
}
}

@ -37,11 +37,20 @@ namespace cat_cafe.Controllers
[MapToApiVersion("1.0")]
public async Task<ActionResult<IEnumerable<CatDto>>> GetCats()
{
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);
}
}
// GET: api/v2/Cats
@ -49,33 +58,54 @@ namespace cat_cafe.Controllers
[MapToApiVersion("2.0")]
public async Task<ActionResult<IEnumerable<CatDto>>> GetCatsV2()
{
try
{
var cats = await _context.Cats.ToListAsync();
_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)
{
try
{
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);
}
}
// PUT: api/v1/Cats/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutCat(long id, CatDto catDto)
{
try
{
if (id != catDto.Id)
{
_logger.LogError("No such cat.");
return BadRequest();
}
@ -84,6 +114,7 @@ namespace cat_cafe.Controllers
if (cat == null)
{
_logger.LogInformation("Cat not found.");
return NotFound();
}
@ -91,37 +122,61 @@ namespace cat_cafe.Controllers
await _context.SaveChangesAsync();
_logger.LogInformation("Cat updated successfully.");
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update cat.");
return BadRequest(ex);
}
}
// POST: api/v1/Cats
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<CatDto>> PostCat(CatDto catDto)
{
try
{
Cat cat = _mapper.Map<Cat>(catDto);
_context.Cats.Add(cat);
await _context.SaveChangesAsync();
await _webSocketHandler.BroadcastMessageAsync("entity-created");
_logger.LogInformation("Cat created successfully.");
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)
{
try
{
var cat = await _context.Cats.FindAsync(id);
if (cat == null)
if (cat != null)
{
return NotFound();
}
_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);
}
}
}
}

@ -29,46 +29,54 @@ namespace cat_cafe.Controllers
[HttpGet]
public async Task<ActionResult<IEnumerable<CustomerDto>>> GetCustomers()
{
Log.Information(this.Request.Method + " => get All customers");
try
{
var customers = await _context.Customers.ToListAsync();
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customers.GetType().ToString() + " length["
+ customers.Count + "]");
_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);
try
{
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{
Log.Information(this.Request.Method + " => " + NotFound().StatusCode.ToString());
_logger.LogInformation("Customer not found.");
return NotFound();
}
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customer.GetType().ToString() + " "
+ JsonConvert.SerializeObject(customer).ToString());
_logger.LogInformation("Customer retrieved successfully.");
return Ok(_mapper.Map<CustomerDto>(customer));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve customer.");
return BadRequest(ex);
}
}
// PUT: api/v1/Customers/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
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");
_logger.LogError("No such customer.");
return BadRequest();
}
@ -77,6 +85,7 @@ namespace cat_cafe.Controllers
if (customer == null)
{
_logger.LogInformation("Customer not found.");
return NotFound();
}
@ -84,50 +93,60 @@ namespace cat_cafe.Controllers
await _context.SaveChangesAsync();
_logger.LogInformation("Customer updated successfully.");
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update customer.");
return BadRequest(ex);
}
}
// POST: api/v1/Customers
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<CustomerDto>> PostCustomer(CustomerDto customerDto)
{
Log.Information(this.Request.Method + " => post customer");
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);
}
}
// DELETE: api/v1/Customers/5
[HttpDelete("{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)
if (customer != null)
{
Log.Information(this.Request.Method + " => " + NotFound().StatusCode.ToString());
return NotFound();
}
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
_logger.LogInformation("Customer deleted successfully.");
}
Log.Information(this.Request.Method + " => "
+ this.Response.StatusCode.ToString() + " "
+ customer.GetType().ToString() + " "
+ JsonConvert.SerializeObject(customer).ToString());
return Ok();
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete customer.");
return BadRequest(ex);
}
}
}
}

@ -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