Merge pull request 'update .net, setup modern logging' (#1) from feat/logging-update into main
All checks were successful
Build and Publish / Build Yale Access Frontend (push) Successful in 45s
Build and Publish / Build Yale Access Backend (push) Successful in 1m54s
Build and Publish / Push Yale Access Frontend Docker Image (push) Successful in 1m22s
Build and Publish / Push Yale Access Backend Docker Image (push) Successful in 1m14s

Reviewed-on: #1
This commit is contained in:
2026-02-18 09:16:25 +11:00
10 changed files with 96 additions and 136 deletions

View File

@@ -25,7 +25,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 7.0.x
dotnet-version: 10.0.x
- name: Restore dependencies
run: dotnet restore

View File

@@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Serilog;
using System.Security.Claims;
using YaleAccess.Models;
@@ -14,15 +13,8 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public class AuthenticationController : ControllerBase
public class AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions, ILogger<AuthenticationController> logger) : ControllerBase
{
private readonly Models.Options.AuthenticationOptions _authenticationOptions;
public AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions)
{
_authenticationOptions = authenticationOptions.Value;
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] string password)
@@ -30,7 +22,7 @@ namespace YaleAccess.Controllers
try
{
// Check if the password is correct
if (password != _authenticationOptions.Password)
if (password != authenticationOptions.Value.Password)
{
return Unauthorized(new ApiResponse("Incorrect password."));
}
@@ -50,7 +42,7 @@ namespace YaleAccess.Controllers
}
catch(Exception ex)
{
Log.Logger.Error(ex, "An error occurred logging in.");
logger.LogError(ex, "An error occurred logging in.");
return BadRequest(new ApiResponse("An error occurred logging in."));
}
}
@@ -68,7 +60,7 @@ namespace YaleAccess.Controllers
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occured logging out.");
logger.LogError(ex, "An error occured logging out.");
return BadRequest(new ApiResponse("An error occured logging out."));
}
}

View File

@@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace YaleAccess.Controllers
{
@@ -9,13 +8,13 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public class HealthController : ControllerBase
public class HealthController(ILogger<HealthController> logger) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
public IActionResult Health()
{
Log.Logger.Information("Hit the health endpoint.");
logger.LogInformation("Hit the health endpoint.");
return Ok("Service is healthy");
}
}

View File

@@ -2,7 +2,6 @@
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Serilog;
using YaleAccess.Data;
using YaleAccess.Models;
@@ -12,27 +11,20 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public class PeopleController : ControllerBase
public class PeopleController(ILogger<PeopleController> logger, YaleContext context) : ControllerBase
{
private readonly YaleContext _context;
public PeopleController(YaleContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetPeople()
{
try
{
// Return all people
List<Person> people = await _context.People.ToListAsync();
List<Person> people = await context.People.ToListAsync();
return Ok(new ApiResponse(people));
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occured retriving the people.");
logger.LogError(ex, "An error occured retriving the people.");
return BadRequest(new ApiResponse("An error occured retriving the people."));
}
}
@@ -46,15 +38,15 @@ namespace YaleAccess.Controllers
Person newPerson = new() { Name = person.Name, PhoneNumber = person.PhoneNumber };
// Add the person
await _context.AddAsync(newPerson);
await _context.SaveChangesAsync();
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occured creating the person.");
logger.LogError(ex, "An error occured creating the person.");
return BadRequest(new ApiResponse("An error occured creating the person."));
}
}
@@ -65,18 +57,18 @@ namespace YaleAccess.Controllers
try
{
// Ensure the person exists
Person person = await _context.People.FindAsync(id) ?? throw new Exception("Person not found.");
Person person = await context.People.FindAsync(id) ?? throw new Exception("Person not found.");
// Remove the person
_context.Remove(person);
await _context.SaveChangesAsync();
context.Remove(person);
await context.SaveChangesAsync();
// Return the newly removed person
return Ok(new ApiResponse(person));
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occured deletiong the person.");
logger.LogError(ex, "An error occured deletiong the person.");
return BadRequest(new ApiResponse("An error occured deletiong the person."));
}
}

View File

@@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Serilog;
using YaleAccess.Models;
using YaleAccess.Models.Options;
using YaleAccess.Services;
@@ -14,33 +13,27 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public class YaleController : ControllerBase
public class YaleController(
ILogger<YaleController> logger,
IYaleAccessor yaleAccessor,
IOptions<CodesOptions> codeOptions,
SMSService smsService
) : ControllerBase
{
private readonly IYaleAccessor _yaleAccessor;
private readonly CodesOptions _codeOptions;
private readonly SMSService _smsService;
public YaleController(IYaleAccessor yaleAccessor, IOptions<CodesOptions> codeOptions, SMSService smsService)
{
_yaleAccessor = yaleAccessor;
_codeOptions = codeOptions.Value;
_smsService = smsService;
}
[HttpGet("codes")]
public async Task<IActionResult> GetUserCodes()
{
try
{
// Get the home code first
YaleUserCode homeCode = await _yaleAccessor.GetCodeInformationAsync(_codeOptions.Home);
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
homeCode.IsHome = true;
// Get the guest codes
List<YaleUserCode> guestCodes = new();
foreach (int code in Enumerable.Range(_codeOptions.GuestCodeRangeStart, _codeOptions.GuestCodeRangeCount))
foreach (int code in Enumerable.Range(codeOptions.Value.GuestCodeRangeStart, codeOptions.Value.GuestCodeRangeCount))
{
guestCodes.Add(await _yaleAccessor.GetCodeInformationAsync(code));
guestCodes.Add(await yaleAccessor.GetCodeInformationAsync(code));
}
// Add the home code to the list
@@ -51,7 +44,7 @@ namespace YaleAccess.Controllers
}
catch(Exception ex)
{
Log.Logger.Error(ex, "An error occurred retriving the codes.");
logger.LogError(ex, "An error occurred retriving the codes.");
return BadRequest(new ApiResponse("An error occurred retriving the codes."));
}
}
@@ -69,23 +62,23 @@ namespace YaleAccess.Controllers
}
// Set the new code
bool result = await _yaleAccessor.SetUserCode(id, newCode);
bool result = await yaleAccessor.SetUserCode(id, newCode);
// Return the result
if (result)
{
Log.Logger.Information("Updated code for user {id} to {code}", id, newCode);
logger.LogInformation("Updated code for user {id} to {code}", id, newCode);
return Ok(new ApiResponse(true));
}
else
{
Log.Logger.Information("Failed to update code for user {id} to {code}", id, newCode);
logger.LogInformation("Failed to update code for user {id} to {code}", id, newCode);
return BadRequest(new ApiResponse("An error occurred setting the code."));
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occurred setting the code.");
logger.LogError(ex, "An error occurred setting the code.");
return BadRequest(new ApiResponse("An error occurred setting the code."));
}
}
@@ -96,30 +89,30 @@ namespace YaleAccess.Controllers
try
{
// First validate the user code
string validCode = YaleAccessor.ValidateClearCode(id, _codeOptions.Home);
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
if (validCode != string.Empty)
{
return BadRequest(new ApiResponse(validCode));
}
// Set the available status
bool result = await _yaleAccessor.SetCodeAsAvailable(id);
bool result = await yaleAccessor.SetCodeAsAvailable(id);
// Return the result
if (result)
{
Log.Logger.Information("Updated code status for user {id} to available", id);
logger.LogInformation("Updated code status for user {id} to available", id);
return Ok(new ApiResponse(true));
}
else
{
Log.Logger.Information("Failed to update code status for user {id} to available", id);
logger.LogInformation("Failed to update code status for user {id} to available", id);
return BadRequest(new ApiResponse("An error occurred setting the code status."));
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occurred setting the code status.");
logger.LogError(ex, "An error occurred setting the code status.");
return BadRequest(new ApiResponse("An error occurred setting the code status."));
}
}
@@ -130,17 +123,17 @@ namespace YaleAccess.Controllers
try
{
// Get the user code
YaleUserCode userCode = await _yaleAccessor.GetCodeInformationAsync(id);
YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// Send the code via SMS to the phone number
await _smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
// Return success
return Ok(new ApiResponse(true));
}
catch (Exception ex)
{
Log.Logger.Error(ex, "An error occurred sending the code.");
logger.LogError(ex, "An error occurred sending the code.");
return BadRequest(new ApiResponse("An error occurred sending the code."));
}
}

View File

@@ -1,8 +1,8 @@
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 8080
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["YaleAccess.csproj", "."]
RUN dotnet restore "./YaleAccess.csproj"

View File

@@ -1,8 +1,7 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Serilog.Events;
using OpenTelemetry.Logs;
using YaleAccess.Data;
using YaleAccess.Models.Options;
using YaleAccess.Services;
@@ -10,15 +9,25 @@ using YaleAccess.Services.Interfaces;
var builder = WebApplication.CreateBuilder(args);
// Create the bootstraper logger
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
if (useOtlpExporter)
{
logging.AddOtlpExporter();
}
else
{
Console.WriteLine("OTEL_EXPORTER_OTLP_ENDPOINT is not set. Skipping OTLP exporter configuration.");
}
});
// Add services to the container.
builder.Services.AddControllers();
@@ -41,15 +50,6 @@ try
// Get a copy of the configuration
IConfiguration configuration = builder.Configuration;
string logLocation = configuration["LogLocation"] ?? "Log.txt";
// Setup the application logger
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Error)
.WriteTo.File(logLocation, rollingInterval: RollingInterval.Day)
.CreateLogger();
// Configure the DI services
builder.Services.AddScoped<SMSService>();
@@ -102,9 +102,6 @@ try
};
});
// Setup logging flow
builder.Host.UseSerilog();
var app = builder.Build();
// Create the database if it doesn't exist
@@ -146,11 +143,7 @@ catch (Exception ex)
// Ignore host aborted exceptions caused by build checks
if (ex is not HostAbortedException)
{
Log.Fatal(ex, "Host terminated unexpectedly");
Console.WriteLine("Host terminated unexpectedly");
throw;
}
}
finally
{
Log.CloseAndFlush();
}

View File

@@ -1,35 +1,27 @@
using Microsoft.Extensions.Options;
using Serilog;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using YaleAccess.Models.Options;
namespace YaleAccess.Services
{
public class SMSService
public class SMSService(ILogger<SMSService> logger, IOptions<TwiloOptions> twiloOptions)
{
private readonly TwiloOptions _twiloOptions;
public SMSService(IOptions<TwiloOptions> twiloOptions)
{
_twiloOptions = twiloOptions.Value;
}
public async Task SendCodeViaSMSAsync(string code, string phoneNumber)
{
// Create a Twilio client
TwilioClient.Init(_twiloOptions.AccountSid, _twiloOptions.AuthToken);
TwilioClient.Init(twiloOptions.Value.AccountSid, twiloOptions.Value.AuthToken);
// Send the message
var message = await MessageResource.CreateAsync(
body: $"{_twiloOptions.Message} {code}",
from: new Twilio.Types.PhoneNumber(_twiloOptions.FromNumber),
body: $"{twiloOptions.Value.Message} {code}",
from: new Twilio.Types.PhoneNumber(twiloOptions.Value.FromNumber),
to: new Twilio.Types.PhoneNumber(phoneNumber)
);
// Log the message
Log.Logger.Information("SMS sent to {PhoneNumber} with message SID {MessageSid}.", phoneNumber, message.Sid);
Log.Logger.Debug("SMS message: {MessageBody}", message.Body);
logger.LogInformation("SMS sent to {PhoneNumber} with message SID {MessageSid}.", phoneNumber, message.Sid);
logger.LogDebug("SMS message: {MessageBody}", message.Body);
}
}
}

View File

@@ -1,6 +1,5 @@
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Serilog;
using System.Diagnostics;
using YaleAccess.Models;
using YaleAccess.Models.Options;
@@ -39,10 +38,11 @@ namespace YaleAccess.Services
#endregion Dispose Logic
private readonly ILogger<YaleAccessor> _logger;
private Driver? driver = null;
private readonly ZWaveNode lockNode = null!;
public YaleAccessor(IOptions<ZWaveOptions> zwave, IOptions<DevicesOptions> device)
public YaleAccessor(IOptions<ZWaveOptions> zwave, IOptions<DevicesOptions> device, ILogger<YaleAccessor> logger)
{
// Retrive options from configuration
ZWaveOptions zwaveOptions = zwave.Value;
@@ -63,13 +63,13 @@ namespace YaleAccess.Services
// Subscribe to the driver ready event
driver.DriverReady += () =>
{
Log.Logger.Information("Z-Wave driver started successfully.");
logger.LogInformation("Z-Wave driver started successfully.");
isReady = true;
};
driver.StartupErrorEvent += (error) =>
{
Log.Logger.Error("Error starting the driver: {error}", error);
logger.LogError("Error starting the driver: {error}", error);
message = error;
};
@@ -83,12 +83,14 @@ namespace YaleAccess.Services
// If there was an error starting the driver, throw an exception
if (message != null)
{
Log.Logger.Error("Failed to start the driver. Error message: {message}", message);
logger.LogError("Failed to start the driver. Error message: {message}", message);
throw new Exception($"Failed to start the driver. Error message: {message}");
}
// Get the lock node from the driver
lockNode = driver.Controller.Nodes.Get(devicesOptions.YaleLockNodeId);
_logger = logger;
}
public async Task<YaleUserCode> GetCodeInformationAsync(int userCodeId)
@@ -97,16 +99,16 @@ namespace YaleAccess.Services
stopwatch.Start();
// Log the start of the operation
Log.Logger.Debug("Retrieving user code information for user code ID: {userCodeId}", userCodeId);
_logger.LogDebug("Retrieving user code information for user code ID: {userCodeId}", userCodeId);
// Setup the two tasks to get the values we need
CMDResult status = await lockNode.GetValue(GetUserStatusValue(userCodeId));
Log.Logger.Debug("Retrieved user code status for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
_logger.LogDebug("Retrieved user code status for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
CMDResult code = await lockNode.GetValue(GetUserCodeValue(userCodeId));
Log.Logger.Debug("Retrieved user code value for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
_logger.LogDebug("Retrieved user code value for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
// Covert the result to a YaleUserCode object
YaleUserCode yaleUserCode = new()
@@ -118,7 +120,7 @@ namespace YaleAccess.Services
};
stopwatch.Stop();
Log.Logger.Debug("Retrieved user code information for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
_logger.LogDebug("Retrieved user code information for user code ID: {userCodeId} in {ElapsedMilliseconds} ms", userCodeId, stopwatch.ElapsedMilliseconds);
// Return the user code information
return yaleUserCode;
@@ -130,7 +132,7 @@ namespace YaleAccess.Services
stopwatch.Start();
// Log the start of the operation
Log.Logger.Debug("Setting user code for user code ID: {userCodeId} to {code}", userCodeId, code);
_logger.LogDebug("Setting user code for user code ID: {userCodeId} to {code}", userCodeId, code);
// Setup the set value task
CMDResult result = await lockNode.SetValue(GetUserCodeValue(userCodeId), code);
@@ -138,11 +140,11 @@ namespace YaleAccess.Services
// If the result is not successful log the message
if (!result.Success)
{
Log.Logger.Error("Failed to set user code {@userCodeId} to {@code}. Error message: {message}", userCodeId, code, result.Message);
_logger.LogError("Failed to set user code {@userCodeId} to {@code}. Error message: {message}", userCodeId, code, result.Message);
}
stopwatch.Stop();
Log.Logger.Debug("Set user code for user code ID: {userCodeId} to {code} in {ElapsedMilliseconds} ms", userCodeId, code, stopwatch.ElapsedMilliseconds);
_logger.LogDebug("Set user code for user code ID: {userCodeId} to {code} in {ElapsedMilliseconds} ms", userCodeId, code, stopwatch.ElapsedMilliseconds);
// Return the result
return result.Success;
@@ -154,7 +156,7 @@ namespace YaleAccess.Services
stopwatch.Start();
// Log the start of the operation
Log.Logger.Debug("Setting user code status for user code ID: {userCode} to available", userCode);
_logger.LogDebug("Setting user code status for user code ID: {userCode} to available", userCode);
// Setup the set value task
CMDResult result = await lockNode.SetValue(GetUserStatusValue(userCode), (int)UserCodeStatus.AVAILABLE);
@@ -162,11 +164,11 @@ namespace YaleAccess.Services
// If the result is not successful log the message
if (!result.Success)
{
Log.Logger.Error("Failed to set user code {@userCode} to available status. Error message: {message}", userCode, result.Message);
_logger.LogError("Failed to set user code {@userCode} to available status. Error message: {message}", userCode, result.Message);
}
stopwatch.Stop();
Log.Logger.Debug("Set user code status for user code ID: {userCode} to available in {ElapsedMilliseconds} ms", userCode, stopwatch.ElapsedMilliseconds);
_logger.LogDebug("Set user code status for user code ID: {userCode} to available in {ElapsedMilliseconds} ms", userCode, stopwatch.ElapsedMilliseconds);
// Return the result
return result.Success;

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>83aa9238-2d6b-483c-b60d-886f32d17532</UserSecretsId>
@@ -17,23 +17,20 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.20">
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Semver" Version="2.3.0" />
<PackageReference Include="Serilog" Version="3.0.1" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.Reactive" Version="5.0.0" />
<PackageReference Include="System.Threading.Channels" Version="5.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="OpenTelemetry" Version="1.15.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.0" />
<PackageReference Include="Semver" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.3" />
<PackageReference Include="System.Reactive" Version="6.1.0" />
<PackageReference Include="Twilio" Version="7.8.0" />
<PackageReference Include="Websocket.Client" Version="4.6.1" />
</ItemGroup>