Skip to content
This repository has been archived by the owner on Aug 14, 2022. It is now read-only.

Commit

Permalink
Added custom logging (via Serilog) (#8)
Browse files Browse the repository at this point in the history
* Added Serilog
* Moved Serilog setup to appsettings
  • Loading branch information
dscpinheiro authored Dec 6, 2019
1 parent f2cb8ae commit b7f339a
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 41 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,5 @@ ASALocalRun/
# MFractors (Xamarin productivity tool) working folder
.mfractor/

.vscode/
.vscode/
/Messages.Api/api-logs
18 changes: 1 addition & 17 deletions Messages.Api/Controllers/MessagesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Messages.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -15,13 +14,8 @@ namespace Messages.Api.Controllers
public class MessagesController : ControllerBase
{
private readonly IMessageService _messagesService;
private readonly ILogger<MessagesController> _logger;

public MessagesController(IMessageService service, ILogger<MessagesController> logger)
{
_messagesService = service;
_logger = logger;
}
public MessagesController(IMessageService service) => _messagesService = service;

/// <summary>
/// Gets all messages, ordered alphabetically.
Expand All @@ -44,8 +38,6 @@ public async Task<ActionResult<IEnumerable<ReadMessageResponse>>> Get(int limit
return BadRequest($"{nameof(offset)} must be at least zero");
}

_logger.LogInformation($"GET /messages LIMIT={limit} OFFSET={offset} TERM={term}");

var messages = await _messagesService.GetAll(limit, offset, term);
return messages.Select(CreateReadModel).ToList();
}
Expand All @@ -59,8 +51,6 @@ public async Task<ActionResult<IEnumerable<ReadMessageResponse>>> Get(int limit
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ReadMessageResponse>> Get(Guid id)
{
_logger.LogInformation($"GET /messages/:id ID={id}");

var message = await _messagesService.GetById(id);
if (message == null)
{
Expand All @@ -79,8 +69,6 @@ public async Task<ActionResult<ReadMessageResponse>> Get(Guid id)
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Post(WriteMessageRequest model)
{
_logger.LogInformation($"POST /messages MESSAGE={model.Message}");

var newMessage = new Message
{
Value = model.Message,
Expand All @@ -102,8 +90,6 @@ public async Task<IActionResult> Post(WriteMessageRequest model)
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Put(Guid id, WriteMessageRequest model)
{
_logger.LogInformation($"PUT /messages/:id ID={id}");

var existingMessage = await _messagesService.GetById(id);
if (existingMessage == null)
{
Expand All @@ -126,8 +112,6 @@ public async Task<IActionResult> Put(Guid id, WriteMessageRequest model)
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id)
{
_logger.LogInformation($"DELETE /messages/:id ID={id}");

var existingMessage = await _messagesService.GetById(id);
if (existingMessage == null)
{
Expand Down
3 changes: 3 additions & 0 deletions Messages.Api/Messages.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.5" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
</ItemGroup>

Expand Down
38 changes: 31 additions & 7 deletions Messages.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,47 @@
using System;
using Messages.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Messages.Api
{
public class Program
{
public static void Main(string[] args)
{
var webHost = CreateHostBuilder(args).Build();
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();

using (var scope = webHost.Services.CreateScope())
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

try
{
var context = scope.ServiceProvider.GetService<ApiDbContext>();
context.Database.Migrate();
}
var webHost = CreateHostBuilder(args).Build();

webHost.Run();
using (var scope = webHost.Services.CreateScope())
{
var context = scope.ServiceProvider.GetService<ApiDbContext>();
context.Database.Migrate();
}

webHost.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Expand All @@ -27,6 +50,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
{
webBuilder.UseUrls("http://*:8080");
webBuilder.UseStartup<Startup>();
});
})
.UseSerilog();
}
}
5 changes: 4 additions & 1 deletion Messages.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Messages.Api.Data;
using Messages.Api.Data;
using Messages.Api.Filters;
using Messages.Api.Services;
using Microsoft.AspNetCore.Builder;
Expand All @@ -8,6 +8,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Serilog;
using System;
using System.IO;
using System.Reflection;
Expand Down Expand Up @@ -73,6 +74,8 @@ public void Configure(IApplicationBuilder app)
options.RoutePrefix = string.Empty;
});

app.UseSerilogRequestLogging();

app.UseRouting();
app.UseAuthorization();
app.UseCors(b => b.AllowAnyMethod().AllowAnyHeader().WithOrigins(Configuration["AllowedHosts"]));
Expand Down
7 changes: 0 additions & 7 deletions Messages.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"API_DB_CONNECTION": "Host=192.168.99.100;Database=postgres;Username=postgres;Password=notthepassword"
}
Expand Down
31 changes: 26 additions & 5 deletions Messages.Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
{
"Logging": {
"LogLevel": {
"Serilog": {
"Using": [
"Serilog.Sinks.Console"
],
"MinimumLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
"Override": {
"Microsoft.AspNetCore": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "./api-logs/log-.json",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"rollingInterval": "Day"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName"
]
},
"AllowedHosts": "*"
}
30 changes: 27 additions & 3 deletions Messages.Tests/Controllers/MessagesControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Messages.Api.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;

Expand All @@ -14,6 +13,7 @@ public partial class MessagesControllerTests : IDisposable
{
private readonly MessagesController _controller;
private readonly ApiDbContext _context;
private bool _isDisposed;

private readonly List<Message> _sampleMessages = new List<Message>
{
Expand Down Expand Up @@ -57,7 +57,12 @@ public MessagesControllerTests()
_context.SaveChanges();

var messagesService = new MessageService(_context);
_controller = new MessagesController(messagesService, NullLogger<MessagesController>.Instance);
_controller = new MessagesController(messagesService);
}

~MessagesControllerTests()
{
Dispose(false);
}

private static DbContextOptions<ApiDbContext> CreateInMemoryOptions()
Expand All @@ -72,6 +77,25 @@ private static DbContextOptions<ApiDbContext> CreateInMemoryOptions()
.Options;
}

public void Dispose() => _context.Dispose();
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool isDisposing)
{
if (_isDisposed)
{
return;
}

if (isDisposing)
{
_context.Dispose();
}

_isDisposed = true;
}
}
}

0 comments on commit b7f339a

Please sign in to comment.