Skip to content
Snippets Groups Projects
Commit 0262f5bb authored by Hindubedu's avatar Hindubedu
Browse files

Merge branch 'main' of https://gitlab.au.dk/bad1/assignment2

parents c8ed53cb 074a6e32
No related branches found
No related tags found
No related merge requests found
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using assignment2.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace assignment2.Controllers
{
[Route("[controller]")]
[ApiController]
public class LogController : ControllerBase
{
private readonly LogsService _logsService;
public LogController(LogsService logsService) => _logsService = logsService;
[HttpGet]
public async Task<IActionResult> GetAsync(string? user, string? operation, DateTime? startDate, DateTime? endTime)
{
var logs = await _logsService.GetAsync(user, operation, startDate, endTime);
return Ok(logs);
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using assignment2.Models;
namespace assignment2.Interfaces
{
public interface ILogService
{
Task<IEnumerable<Log>> GetAsync(string? user, string? operation, DateTime? startDate, DateTime? endTime);
}
}
\ No newline at end of file
using System.Diagnostics;
using assignment2.Interfaces;
using assignment2.Models;
public sealed class LoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly ILogService _logService;
public LoggerMiddleware(RequestDelegate next, ILogger<LoggerMiddleware> logger)
public LoggerMiddleware(RequestDelegate next, ILogger<LoggerMiddleware> logger, ILogService logService)
{
_next = next;
_logger = logger;
_logService = logService;
}
public async Task Invoke(HttpContext context)
......@@ -22,13 +26,14 @@ public sealed class LoggerMiddleware
// Add other details as needed
};
// Optionally, add user info if available.
if (context.User?.Identity?.IsAuthenticated == true)
var newLog = new Log
{
requestDetails["UserName"] = context.User?.Identity?.Name;
}
User = context.User?.Identity?.Name ?? "Anonymous",
Operation = context.Request.Method,
Timestamp = DateTime.UtcNow
};
_logger.LogInformation("Request completed with details: {@RequestDetails}", requestDetails);
_logger.LogInformation("Request completed with details: {@newLog}", newLog);
await _next(context);
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace assignment2.Models
{
public class Log
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("api_user")]
public string User { get; set; } = string.Empty;
[BsonElement("operation")]
public string Operation { get; set; } = string.Empty;
[BsonElement("timestamp")]
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace assignment2.Models
{
public class LogsDatabaseSettings
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
public string LogsCollectionName { get; set; } = null!;
}
}
\ No newline at end of file
......@@ -6,9 +6,14 @@ using ZiggyCreatures.Caching.Fusion;
using Microsoft.Extensions.Caching.Memory;
using Serilog;
using Microsoft.Extensions.Options;
using assignment2.Models;
using assignment2.Interfaces;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.Configure<LogsDatabaseSettings>(
builder.Configuration.GetSection("LoggingDB"));
// Add services to the container.
builder.Services.AddControllers();
......@@ -17,6 +22,7 @@ builder.Services.AddTransient<IExperienceService, ExperienceService>();
builder.Services.AddTransient<IProviderService, ProviderService>();
builder.Services.AddTransient<ISharedExperienceService, SharedExperienceService>();
builder.Services.AddTransient<IGuestService, GuestService>();
builder.Services.AddSingleton<ILogService, LogsService>();
Env.Load();
builder.Services.AddDbContext<ExperienceDBContext>();
builder.Services.AddFusionCache().WithDefaultEntryOptions(new FusionCacheEntryOptions
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using assignment2.Interfaces;
using assignment2.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
namespace assignment2.Services
{
public class LogsService : ILogService
{
private readonly IMongoCollection<Log> _logsCollection;
public LogsService(IOptions<LogsDatabaseSettings> logsDatabaseSettings)
{
var mongoClient = new MongoClient(
logsDatabaseSettings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(
logsDatabaseSettings.Value.DatabaseName);
_logsCollection = mongoDatabase.GetCollection<Log>(
logsDatabaseSettings.Value.LogsCollectionName);
}
public async Task<IEnumerable<Log>> GetAsync(string? user, string? operation, DateTime? startDate, DateTime? endTime)
{
var builder = Builders<Log>.Filter;
var filters = new List<FilterDefinition<Log>>();
if (!string.IsNullOrEmpty(user))
filters.Add(builder.Eq(u => u.User, user));
if (!string.IsNullOrEmpty(operation))
filters.Add(builder.Eq(u => u.Operation, operation));
if (startDate.HasValue && endTime.HasValue)
filters.Add(builder.And(builder.Gte(u => u.Timestamp, startDate), builder.Lte(u => u.Timestamp, endTime)));
var filter = filters.Count > 0 ? builder.And(filters) : builder.Empty;
return await _logsCollection.Find(filter).ToListAsync();
}
}
}
\ No newline at end of file
{
"LoggingDB": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "AssignmentLoggingDB",
"LogsCollectionName": "Logs"
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment