Skip to content

Commit

Permalink
WIP on replacing DbLogger with Serilog.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbound committed May 16, 2023
1 parent c1fffe2 commit 1a79650
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 271 deletions.
42 changes: 23 additions & 19 deletions Server/API/AgentUpdateController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,32 +27,28 @@ public class AgentUpdateController : ControllerBase


private readonly IHubContext<AgentHub> _agentHubContext;

private readonly ILogger<AgentUpdateController> _logger;
private readonly IApplicationConfig _appConfig;

private readonly IDataService _dataService;

private readonly IWebHostEnvironment _hostEnv;

private readonly IServiceHubSessionCache _serviceSessionCache;

public AgentUpdateController(IWebHostEnvironment hostingEnv,
IDataService dataService,
IApplicationConfig appConfig,
IServiceHubSessionCache serviceSessionCache,
IHubContext<AgentHub> agentHubContext)
IHubContext<AgentHub> agentHubContext,
ILogger<AgentUpdateController> logger)
{
_hostEnv = hostingEnv;
_dataService = dataService;
_appConfig = appConfig;
_serviceSessionCache = serviceSessionCache;
_agentHubContext = agentHubContext;
_logger = logger;
}

[HttpGet("[action]/{downloadId}")]
public ActionResult ClearDownload(string downloadId)
{
_dataService.WriteEvent($"Clearing download ID {downloadId}.", EventType.Debug, null);
_logger.LogDebug("Clearing download ID {downloadId}.", downloadId);
_downloadingAgents.Remove(downloadId);
return Ok();
}
Expand Down Expand Up @@ -92,10 +88,16 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
_downloadingAgents.Set(downloadId, string.Empty, cacheOptions);

var waitTime = DateTimeOffset.Now - startWait;
_dataService.WriteEvent($"Download started after wait time of {waitTime}. " +
$"ID: {downloadId}. " +
$"IP: {remoteIp}. " +
$"Current Downloads: {_downloadingAgents.Count}. Max Allowed: {_appConfig.MaxConcurrentUpdates}", EventType.Debug, null);
_logger.LogDebug(
"Download started after wait time of {waitTime}. " +
"ID: {downloadId}. " +
"IP: {remoteIp}. " +
"Current Downloads: {_downloadingAgentsCount}. Max Allowed: {_appConfigMaxConcurrentUpdates}",
waitTime,
downloadId,
remoteIp,
_downloadingAgents.Count,
_appConfig.MaxConcurrentUpdates);


string filePath;
Expand All @@ -115,11 +117,13 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
filePath = Path.Combine(_hostEnv.WebRootPath, "Content", "Remotely-MacOS-x64.zip");
break;
default:
_dataService.WriteEvent($"Unknown platform requested in {nameof(AgentUpdateController)}. " +
$"Platform: {platform}. " +
$"IP: {remoteIp}.",
EventType.Warning,
null);
_logger.LogWarning(
"Unknown platform requested in {className}. " +
"Platform: {platform}. " +
"IP: {remoteIp}.",
nameof(AgentUpdateController),
platform,
remoteIp);
return BadRequest();
}

Expand All @@ -130,7 +134,7 @@ public async Task<ActionResult> DownloadPackage(string platform, string download
catch (Exception ex)
{
_downloadingAgents.Remove(downloadId);
_dataService.WriteEvent(ex, null);
_logger.LogError(ex, "Error while downloading package.");
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
Expand Down
20 changes: 14 additions & 6 deletions Server/API/AlertsController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;
using Remotely.Server.Auth;
using Remotely.Server.Services;
using Remotely.Shared.Models;
Expand All @@ -20,20 +22,26 @@ public class AlertsController : ControllerBase
private readonly IDataService _dataService;
private readonly IEmailSenderEx _emailSender;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<AlertsController> _logger;

public AlertsController(IDataService dataService, IEmailSenderEx emailSender, IHttpClientFactory httpClientFactory)
public AlertsController(
IDataService dataService,
IEmailSenderEx emailSender,
IHttpClientFactory httpClientFactory,
ILogger<AlertsController> logger)
{
_dataService = dataService;
_emailSender = emailSender;
_httpClientFactory = httpClientFactory;
_logger = logger;
}

[HttpPost("Create")]
public async Task<IActionResult> Create(AlertOptions alertOptions)
{
Request.Headers.TryGetValue("OrganizationID", out var orgID);

_dataService.WriteEvent("Alert created. Alert Options: " + JsonSerializer.Serialize(alertOptions), orgID);
_logger.LogInformation("Alert created. Alert Options: {options}", JsonSerializer.Serialize(alertOptions));

if (alertOptions.ShouldAlert)
{
Expand All @@ -43,7 +51,7 @@ public async Task<IActionResult> Create(AlertOptions alertOptions)
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while adding alert.");
}
}

Expand All @@ -58,7 +66,7 @@ await _emailSender.SendEmailAsync(alertOptions.EmailTo,
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while sending email.");
}

}
Expand All @@ -81,11 +89,11 @@ await _emailSender.SendEmailAsync(alertOptions.EmailTo,
}

using var response = await httpClient.SendAsync(request);
_dataService.WriteEvent($"Alert API Response Status: {response.StatusCode}.", orgID);
_logger.LogInformation("Alert API Response Status: {responseStatusCode}.", response.StatusCode);
}
catch (Exception ex)
{
_dataService.WriteEvent(ex, orgID);
_logger.LogError(ex, "Error while sending alert API request.");
}

}
Expand Down
17 changes: 11 additions & 6 deletions Server/API/LoginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Build.Framework;
using Microsoft.Extensions.Logging;
using Remotely.Server.Hubs;
using Remotely.Server.Models;
using Remotely.Server.Services;
Expand All @@ -24,21 +26,24 @@ public class LoginController : ControllerBase
private readonly IDesktopHubSessionCache _desktopSessionCache;
private readonly SignInManager<RemotelyUser> _signInManager;
private readonly IHubContext<ViewerHub> _viewerHub;
private readonly ILogger<LoginController> _logger;

public LoginController(
SignInManager<RemotelyUser> signInManager,
IDataService dataService,
IApplicationConfig appConfig,
IHubContext<DesktopHub> casterHubContext,
IDesktopHubSessionCache desktopSessionCache,
IHubContext<ViewerHub> viewerHubContext)
IHubContext<ViewerHub> viewerHubContext,
ILogger<LoginController> logger)
{
_signInManager = signInManager;
_dataService = dataService;
_appConfig = appConfig;
_desktopHub = casterHubContext;
_desktopSessionCache = desktopSessionCache;
_viewerHub = viewerHubContext;
_logger = logger;
}

[HttpGet("Logout")]
Expand All @@ -60,7 +65,7 @@ public async Task<IActionResult> Logout()
}
}
await _signInManager.SignOutAsync();
_dataService.WriteEvent($"API logout successful for {HttpContext?.User?.Identity?.Name}.", orgId);
_logger.LogInformation("API logout successful for {userName}.", HttpContext?.User?.Identity?.Name);
return Ok();
}

Expand All @@ -77,20 +82,20 @@ public async Task<IActionResult> Post([FromBody] ApiLogin login)
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, true);
if (result.Succeeded)
{
_dataService.WriteEvent($"API login successful for {login.Email}.", orgId);
_logger.LogInformation("API login successful for {loginEmail}.", login.Email);
return Ok();
}
else if (result.IsLockedOut)
{
_dataService.WriteEvent($"API login unsuccessful due to lockout for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to lockout for {loginEmail}.", login.Email);
return Unauthorized("Account is locked.");
}
else if (result.RequiresTwoFactor)
{
_dataService.WriteEvent($"API login unsuccessful due to 2FA for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to 2FA for {loginEmail}.", login.Email);
return Unauthorized("Account requires two-factor authentication.");
}
_dataService.WriteEvent($"API login unsuccessful due to bad attempt for {login.Email}.", orgId);
_logger.LogInformation("API login unsuccessful due to bad attempt for {loginEmail}.", login.Email);
return BadRequest();
}
}
Expand Down
1 change: 0 additions & 1 deletion Server/Data/AppDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public class AppDb : IdentityDbContext
public DbSet<BrandingInfo> BrandingInfos { get; set; }
public DbSet<DeviceGroup> DeviceGroups { get; set; }
public DbSet<Device> Devices { get; set; }
public DbSet<EventLog> EventLogs { get; set; }
public DbSet<InviteLink> InviteLinks { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<ScriptRun> ScriptRuns { get; set; }
Expand Down
54 changes: 48 additions & 6 deletions Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@
using Remotely.Shared.Services;
using System;
using Immense.RemoteControl.Server.Services;
using Serilog;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var services = builder.Services;

builder.Logging.ClearProviders();
ConfigureSerilog(builder);

builder.Host.UseSerilog();

builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
builder.Logging.AddConsole();
builder.Logging.AddDebug();

if (OperatingSystem.IsWindows() &&
bool.TryParse(builder.Configuration["ApplicationOptions:EnableWindowsEventLog"], out var enableEventLog) &&
Expand Down Expand Up @@ -111,6 +113,7 @@
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<RemotelyUser>>();
services.AddDatabaseDeveloperPageExceptionFilter();

if (bool.TryParse(configuration["ApplicationOptions:UseHttpLogging"], out var useHttpLogging) &&
useHttpLogging)
{
Expand All @@ -125,6 +128,7 @@
options.RequestHeaders.Add("Host");
});
}

var trustedOrigins = configuration.GetSection("ApplicationOptions:TrustedCorsOrigins").Get<string[]>();

if (trustedOrigins != null)
Expand Down Expand Up @@ -265,7 +269,6 @@
{
using var context = scope.ServiceProvider.GetRequiredService<AppDb>();
var dataService = scope.ServiceProvider.GetRequiredService<IDataService>();
var loggerFactory = scope.ServiceProvider.GetRequiredService<ILoggerFactory>();

if (context.Database.IsRelational())
{
Expand All @@ -274,8 +277,6 @@

await dataService.SetAllDevicesNotOnline();
dataService.CleanupOldRecords();

loggerFactory.AddProvider(new DbLoggerProvider(app.Environment, app.Services));
}

await app.RunAsync();
Expand Down Expand Up @@ -315,4 +316,45 @@ void ConfigureStaticFiles()
ServeUnknownFileTypes = true
});
}
}

void ConfigureSerilog(WebApplicationBuilder webAppBuilder)
{
try
{
var dataRetentionDays = 7;
if (int.TryParse(webAppBuilder.Configuration["ApplicationOptions:DataRetentionInDays"], out var retentionSetting))
{
dataRetentionDays = retentionSetting;
}

var logPath = Directory.Exists("/remotely-data") ? "/remotely-data/logs" : "logs";
Directory.CreateDirectory(logPath);

void ApplySharedLoggerConfig(LoggerConfiguration loggerConfiguration)
{
loggerConfiguration
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File($"{logPath}/Remotely_Server.log", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(dataRetentionDays));
}

var loggerConfig = new LoggerConfiguration();
ApplySharedLoggerConfig(loggerConfig);
Log.Logger = loggerConfig.CreateBootstrapLogger();

builder.Host.UseSerilog((context, services, configuration) =>
{
configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services);

ApplySharedLoggerConfig(configuration);
});
}
catch (Exception ex)
{
Console.WriteLine($"Failed to configure Serilog file logging. Error: {ex.Message}");
}
}
1 change: 1 addition & 0 deletions Server/Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
Loading

0 comments on commit 1a79650

Please sign in to comment.