Skip to content

Commit

Permalink
Add initial logging support via serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
EjPlatzer committed Apr 12, 2024
1 parent 2c234c7 commit 038e1d2
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 142 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,6 @@ paket-files/
# Environment Specific app settings
appsettings.*.json
secrets.config

# Logs
Gordon360/Logs/*
68 changes: 1 addition & 67 deletions Gordon360/Documentation/Gordon360.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Gordon360/Gordon360.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@
<ItemGroup>
<PackageReference Include="Microsoft.Graph" Version="4.27.0" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.23.1" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" />
Expand All @@ -71,6 +76,9 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
<PropertyGroup>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
</PropertyGroup>
Expand Down
176 changes: 102 additions & 74 deletions Gordon360/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,109 +12,137 @@
using Microsoft.Extensions.FileProviders;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;
using Serilog;
using Serilog.Formatting.Compact;
using System;
using System.Collections.Generic;
using System.IO;
using RecIM = Gordon360.Services.RecIM;

var builder = WebApplication.CreateBuilder(args);
const string CorsPolicy = "360UI";

var azureConfig = builder.Configuration.GetSection("AzureAd").Get<AzureAdConfig>();
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateBootstrapLogger();

// Add services to the container.
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd");

builder.Services.AddControllers(options =>
try
{
options.OutputFormatters.RemoveType<StringOutputFormatter>(); // Return strings as application/json instead of text/plain
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); // Return null as 200 Ok null instead of 204 No Content
}).AddNewtonsoftJson(options => options.UseMemberCasing());
var builder = WebApplication.CreateBuilder(args);

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
builder.Services.AddSerilog((services, lc) => lc
.ReadFrom.Configuration(builder.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(new CompactJsonFormatter(), "./Logs/info.json", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 14, rollOnFileSizeLimit: true)
.WriteTo.File(new CompactJsonFormatter(), "./Logs/error.json", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error, rollingInterval: RollingInterval.Day));

builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd");

builder.Services.AddControllers(options =>
{
options.OutputFormatters.RemoveType<StringOutputFormatter>(); // Return strings as application/json instead of text/plain
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); // Return null as 200 Ok null instead of 204 No Content
}).AddNewtonsoftJson(options => options.UseMemberCasing());

builder.Services.AddEndpointsApiExplorer();

var azureConfig = builder.Configuration.GetSection("AzureAd").Get<AzureAdConfig>();

builder.Services.AddSwaggerGen(c =>
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
AuthorizationCode = new OpenApiOAuthFlow()
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{azureConfig.TenantId}/oauth2/v2.0/authorize"),
TokenUrl = new Uri($"https://login.microsoftonline.com/{azureConfig.TenantId}/oauth2/v2.0/token"),
Scopes = new Dictionary<string, string> {
AuthorizationCode = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{azureConfig.TenantId}/oauth2/v2.0/authorize"),
TokenUrl = new Uri($"https://login.microsoftonline.com/{azureConfig.TenantId}/oauth2/v2.0/token"),
Scopes = new Dictionary<string, string> {
{
$"{azureConfig.Audience}/access_as_user",
"Access 360 as you."
}
}
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "oauth2",
In = ParameterLocation.Header
},
new List<string>()
}
});
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {

builder.Services.AddCors(p => p.AddPolicy(name: CorsPolicy, corsBuilder =>
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "oauth2",
In = ParameterLocation.Header
},
new List < string > ()
}
});
}
);
corsBuilder.WithOrigins(builder.Configuration.GetValue<string>("AllowedOrigin")).AllowAnyMethod().AllowAnyHeader();
}));

string corsPolicy = "360UI";
builder.Services.AddCors(p => p.AddPolicy(name: corsPolicy, corsBuilder =>
{
corsBuilder.WithOrigins(builder.Configuration.GetValue<string>("AllowedOrigin")).AllowAnyMethod().AllowAnyHeader();
}));
builder.Services.AddDbContext<CCTContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("CCT"))
).AddDbContext<MyGordonContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyGordon"))
).AddDbContext<webSQLContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("webSQL"))
);

builder.Services.AddDbContext<CCTContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("CCT"))
).AddDbContext<MyGordonContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyGordon"))
).AddDbContext<webSQLContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("webSQL"))
);
builder.Services.Add360Services();
builder.Services.AddHostedService<EventCacheRefreshService>();
builder.Services.AddScoped<ServerUtils, ServerUtils>();

builder.Services.Add360Services();
builder.Services.AddHostedService<EventCacheRefreshService>();
builder.Services.AddScoped<ServerUtils, ServerUtils>();
builder.Services.AddMemoryCache();

builder.Services.AddMemoryCache();
var app = builder.Build();

var app = builder.Build();
// Configure the HTTP request pipeline.

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(azureConfig.ClientId);
c.OAuthScopes($"{azureConfig.Audience}/access_as_user");
c.OAuthUsePkce();
});

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(azureConfig.ClientId);
c.OAuthScopes($"{azureConfig.Audience}/access_as_user");
c.OAuthUsePkce();
});
app.UseSerilogRequestLogging();

app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "browseable")),
RequestPath = "/browseable"
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "browseable")),
RequestPath = "/browseable"
});

app.UseRouting();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
app.UseAuthentication();
app.UseAuthorization();

app.UseCors(corsPolicy);
app.UseCors(CorsPolicy);

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

app.Run();

// Only runs once the app shutsdown
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "An unhandled exception occurred during startup");
return 1;
}
finally
{
Log.CloseAndFlush();
}

app.Run();
13 changes: 12 additions & 1 deletion Gordon360/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"AllowedHosts": "localhost;360.gordon.edu",
"AllowedOrigin": "<Default>",
"AllowedOrigin": "<Default>",
"AzureAd": {
"Instance": "<Default>",
"ClientId": "<Default>",
Expand Down Expand Up @@ -37,5 +37,16 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore.Mvc": "Warning",
"Microsoft.AspNetCore.Routing": "Warning",
"Microsoft.AspNetCore.Hosting": "Warning"
}
}
},
"SmtpHost": "smtp.gordon.edu"
}

0 comments on commit 038e1d2

Please sign in to comment.