Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logging #13

Merged
merged 4 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions TinyUrl/Controllers/UrlController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@ public class UrlController : ControllerBase
private readonly IUrlRepository _urlRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IDistributedCache _cache;
private readonly ILogger<UrlController> _logger;

public UrlController(IUrlConverter urlConverter, IUrlRepository urlRepository, IUnitOfWork unitOfWork, IDistributedCache cache)
public UrlController(IUrlConverter urlConverter,
IUrlRepository urlRepository,
IUnitOfWork unitOfWork,
IDistributedCache cache,
ILogger<UrlController> logger)
{
this._urlConverter = urlConverter;
this._urlRepository = urlRepository;
this._unitOfWork = unitOfWork;
this._cache = cache;
this._logger = logger;
}

[HttpPost("shorten")]
Expand Down Expand Up @@ -48,9 +54,10 @@ public async Task<IActionResult> RedirectToLongUrl(string shortUrlHash, Cancella
var urlString = await this._cache.GetStringAsync(shortUrlHash, cancellationToken);
if (!string.IsNullOrEmpty(urlString))
{
this._logger.LogInformation("Cache hit for {shortUrlHash}", shortUrlHash);
return this.Redirect(urlString);
}

this._logger.LogInformation("Cache miss for {shortUrlHash}", shortUrlHash);
var url = await this._urlRepository.TryGetUrlByCodeAsync(shortUrlHash, cancellationToken);
urlString = url?.ToString();
if (string.IsNullOrEmpty(urlString))
Expand Down
56 changes: 39 additions & 17 deletions TinyUrl/Program.cs
Original file line number Diff line number Diff line change
@@ -1,30 +1,52 @@
using Serilog;
using TinyUrl.Controllers;
using TinyUrl.Logic;
using TinyUrl.Repository;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
try
{

// Add services to the container.
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.WriteTo.File("logs.txt")
.CreateLogger();

var services = builder.Services;
services.AddDataDependencies(configuration);
services.AddApiDependencies();
services.AddBusinessLogicDependencies();
var app = builder.Build();
// Add services to the container.

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Configure the HTTP request pipeline.
var services = builder.Services;
services.AddSerilog();
services.AddDataDependencies(configuration);
services.AddApiDependencies();
services.AddBusinessLogicDependencies();
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseSerilogRequestLogging();
app.UseAuthorization();

app.UseAuthorization();
app.MapControllers();

app.MapControllers();
app.Run();
return 0;
}
catch (Exception e)
{
Log.Fatal(e, "Host terminated unexpectedly");
return 1;

app.Run();
}
finally
{
await Log.CloseAndFlushAsync();
}

// to test using web application factory
public partial class Program { }
7 changes: 6 additions & 1 deletion TinyUrl/Repository/SqlRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ namespace TinyUrl.Repository
public class SqlRepository : IUrlRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<SqlRepository> _logger;

public SqlRepository(ApplicationDbContext dbContext)
public SqlRepository(ApplicationDbContext dbContext, ILogger<SqlRepository> logger)
{
this._dbContext = dbContext;
this._logger = logger;
}

public async Task<int> GenerateIdAsync(Uri url, CancellationToken cancellationToken)
Expand All @@ -17,6 +19,7 @@ public async Task<int> GenerateIdAsync(Uri url, CancellationToken cancellationTo
var urlMappings = new UrlMappings { Url = url.ToString() };
this._dbContext.Urls.Add(urlMappings);
await this._dbContext.SaveChangesAsync(cancellationToken);
this._logger.LogInformation("Generated id {id} for {url}", urlMappings.Id, url);
return urlMappings.Id;
}

Expand All @@ -30,12 +33,14 @@ public async Task<bool> TryUpdateCodeAsync(int id, string code, CancellationToke

urlMappings.Code = code;
await this._dbContext.SaveChangesAsync(cancellationToken);
this._logger.LogInformation("Updated code {code} for id {id}", code, id);
return true;
}

public async Task<Uri?> TryGetUrlByCodeAsync(string code, CancellationToken cancellationToken)
{
var urlMappings = await this._dbContext.Urls.FirstOrDefaultAsync(x => x.Code == code, cancellationToken);
this._logger.LogInformation("Retrieved url {url} for code {code}", urlMappings?.Url, code);
return urlMappings == null ? null : new Uri(urlMappings.Url!);
}
}
Expand Down
6 changes: 6 additions & 0 deletions TinyUrl/TinyUrl.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.ColoredConsole" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.10" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.8.1" />
Expand Down
30 changes: 25 additions & 5 deletions TinyUrl/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
"Serilog": {
"MinimumLevel": {
"Default": "Information", // Default log level
"Override": {
"Microsoft": "Warning", // Override Microsoft logs to Warning level
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], // Enrichment
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
},
"ConnectionStrings": {
"Sql": "Server=localhost,1433;Database=TinyUrl;User Id=sa;Password=111111111111111@Q;TrustServerCertificate=True;",
Expand Down