Skip to content

Commit 4ae506c

Browse files
Lanning, MarkLanning, Mark
authored andcommitted
Refactor logging and improve code readability
- Cleaned up `Telemetry.cs` by removing unnecessary comments and updating the `Tags` property to a dictionary. - Enhanced logging in `Database.cs` and `DataContext.cs` to use Serilog instead of `Console.WriteLine`. - Added `Configuration.cs` with `TryGetConnectionString` method for improved connection string retrieval and logging. - Updated project references in `ThingsLibrary.Database.csproj` and `ThingsLibrary.Entity.csproj` to point to `ThingsLibrary.Services`. - Refactored `Logger.cs` for better Serilog initialization and removed commented-out code. - Updated global using directives in `Usings.cs` to reflect new namespace structure.
1 parent 99b5fb8 commit 4ae506c

File tree

9 files changed

+59
-147
lines changed

9 files changed

+59
-147
lines changed

Base/src/ThingsLibrary.Base/DataType/Events/Telemetry.cs

Lines changed: 0 additions & 86 deletions
This file was deleted.

Database/src/ThingsLibrary.Database.SqlServer/Extensions/Database.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// </copyright>
66
// ================================================================================
77

8+
using Serilog;
89
using ThingsLibrary.Services.Extensions;
910

1011
namespace ThingsLibrary.Database.SqlServer.Extensions
@@ -42,11 +43,11 @@ public static IServiceCollection AddDatabaseSqlServer<TContext>(this IServiceCol
4243
// verify a SQL connection can be established before continuing
4344
using (var connection = new SqlConnection(connectionString))
4445
{
45-
Console.WriteLine($"Testing SQL Connection to {connection.DataSource}...");
46+
Log.Information("Testing SQL Connection to {DatabaseServer}...", connection.DataSource);
4647
connection.Open();
4748

48-
Console.WriteLine($"+ SQL Server: {connection.DataSource} ");
49-
Console.WriteLine($"+ SQL Database: {connection.Database}");
49+
Log.Information("+ SQL Server: {DatabaseServer}", connection.DataSource);
50+
Log.Information("+ SQL Database: {DatabaseName}", connection.Database);
5051
}
5152

5253
services.AddDbContext<TContext>(builder => builder.Configure<TContext>(connectionString));

Database/src/ThingsLibrary.Database/DataContext.cs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
// </copyright>
66
// ================================================================================
77

8+
using Serilog;
9+
810
namespace ThingsLibrary.Database
911
{
1012
// ====================================================================================
@@ -42,14 +44,6 @@ public DataContext(DbContextOptions options) : base(options)
4244
//nothing
4345
}
4446

45-
//protected override void OnConfiguring(DbContextOptionsBuilder options)
46-
//{
47-
// //TODO:
48-
// Console.WriteLine("OnConfiguring()");
49-
// //optionsBuilder.EnableSensitiveDataLogging();
50-
//}
51-
52-
5347
/// <summary>
5448
/// On Model Creating
5549
/// </summary>
@@ -63,22 +57,22 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
6357
// include all of the services fluent API configurations
6458
var baseAssembly = typeof(DataContext).Assembly;
6559

66-
Console.WriteLine($"= Applying {baseAssembly.GetName().Name} ({baseAssembly.GetName().Version}) Configurations...");
60+
Log.Information("= Applying {AssemblyName} ({AssemblyVersion}) Configurations...", baseAssembly.GetName().Name, baseAssembly.GetName().Version);
6761
modelBuilder.ApplyConfigurationsFromAssembly(baseAssembly);
6862

6963
var assembly = this.GetType().Assembly;
7064
if (assembly != baseAssembly)
7165
{
72-
Console.WriteLine($"= Applying {assembly.GetName().Name} ({assembly.GetName().Version}) Configurations...");
66+
Log.Information("= Applying {AssemblyName} ({AssemblyVersion}) Configurations...", assembly.GetName().Name, assembly.GetName().Version);
7367
modelBuilder.ApplyConfigurationsFromAssembly(assembly);
7468
}
7569

7670
//turn off default OnDelete:cascade
77-
Console.WriteLine($"= Restricting Delete behaviors...");
71+
Log.Information($"= Restricting Delete behaviors...");
7872
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
7973
{
8074
relationship.DeleteBehavior = DeleteBehavior.Restrict;
81-
}
75+
}
8276
}
8377

8478
/// <summary>
@@ -94,6 +88,7 @@ public void CreateIndexes<T>(EntityTypeBuilder<T> builder) where T : class
9488
var partitionKey = type.GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(Attributes.PartitionKeyAttribute), false).Any());
9589
if (partitionKey != null)
9690
{
91+
Log.Information("= Creating Partition Key Index on {EntityType}.{PartitionKey}", type.Name, partitionKey.Name);
9792
builder.HasIndex(partitionKey.Name);
9893
}
9994

@@ -114,7 +109,7 @@ public void CreateIndexes<T>(EntityTypeBuilder<T> builder) where T : class
114109
/// <param name="modelBuilder"></param>
115110
public void SeedBaseData(ModelBuilder modelBuilder)
116111
{
117-
Console.WriteLine("= Seeding / Validating Base Database Data...");
112+
Log.Information("= Seeding / Validating Base Database Data...");
118113

119114
// EXAMPLE:
120115
//modelBuilder.Entity<EventType>().HasData(

Database/src/ThingsLibrary.Database/ThingsLibrary.Database.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
</ItemGroup>
4343

4444
<ItemGroup>
45-
<ProjectReference Include="..\..\..\Base\src\ThingsLibrary.Base\ThingsLibrary.csproj" />
45+
<ProjectReference Include="..\..\..\Services\src\ThingsLibrary.Services\ThingsLibrary.Services.csproj" />
4646
</ItemGroup>
4747

4848
</Project>

Entity/src/ThingsLibrary.Entity/DataContext.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
// </copyright>
66
// ================================================================================
77

8+
using Serilog;
9+
810
namespace ThingsLibrary.Entity
911
{
1012
public class DataContext : DbContext
@@ -32,22 +34,22 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
3234
// include all of the services fluent API configurations
3335
var baseAssembly = typeof(DataContext).Assembly;
3436

35-
Console.WriteLine($"= Applying {baseAssembly.GetName().Name} ({baseAssembly.GetName().Version}) Configurations...");
37+
Log.Information("= Applying {AssemblyName} ({AssemblyVersion}) Configurations...", baseAssembly.GetName().Name, baseAssembly.GetName().Version);
3638
modelBuilder.ApplyConfigurationsFromAssembly(baseAssembly);
3739

3840
var assembly = this.GetType().Assembly;
3941
if (assembly != baseAssembly)
4042
{
41-
Console.WriteLine($"= Applying {assembly.GetName().Name} ({assembly.GetName().Version}) Configurations...");
43+
Log.Information("= Applying {AssemblyName} ({AssemblyVersion}) Configurations...", assembly.GetName().Name, assembly.GetName().Version);
4244
modelBuilder.ApplyConfigurationsFromAssembly(assembly);
4345
}
4446

45-
//turn off default OnDelete:cascade
46-
Console.WriteLine($"= Restricting Delete behaviors...");
47+
//turn off default OnDelete:cascade
48+
Log.Information($"= Restricting Delete behaviors...");
4749
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
4850
{
4951
relationship.DeleteBehavior = DeleteBehavior.Restrict;
50-
}
52+
}
5153
}
5254

5355
/// <summary>

Entity/src/ThingsLibrary.Entity/ThingsLibrary.Entity.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
</ItemGroup>
3232

3333
<ItemGroup>
34-
<ProjectReference Include="..\..\..\Base\src\ThingsLibrary.Base\ThingsLibrary.csproj" />
34+
<ProjectReference Include="..\..\..\Services\src\ThingsLibrary.Services\ThingsLibrary.Services.csproj" />
3535
</ItemGroup>
3636

3737
</Project>

Database/src/ThingsLibrary.Database/Extensions/Configuration.cs renamed to Services/src/ThingsLibrary.Services/Extensions/Configuration.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
namespace ThingsLibrary.Services.Extensions
99
{
1010
public static class ConfigurationExtensions
11-
{
11+
{
1212
/// <summary>
1313
/// Get connection string in the various places it could be.
1414
/// </summary>
@@ -21,30 +21,30 @@ public static string TryGetConnectionString(this IConfiguration configuration, s
2121
{
2222
if (string.IsNullOrEmpty(connectionStringName)) { throw new ArgumentNullException(nameof(connectionStringName)); }
2323

24-
Console.WriteLine($"Getting connection string '{connectionStringName}'...");
24+
Log.Debug("Getting connection string '{ConnectionStringName}'...", connectionStringName);
2525
var connectionString = configuration.GetConnectionString(connectionStringName);
2626
if (string.IsNullOrEmpty(connectionString))
2727
{
28-
Console.WriteLine($"Not Found; Trying to get 'CUSTOMCONNSTR_{connectionStringName}' with Prefix...");
28+
Log.Debug("Not Found; Trying to get '{ConnectionStringName}' with Prefix...", $"CUSTOMCONNSTR_{connectionStringName}");
2929
connectionString = configuration.GetConnectionString($"CUSTOMCONNSTR_{connectionStringName}");
3030
}
31-
31+
3232
if (string.IsNullOrEmpty(connectionString))
3333
{
34-
Console.WriteLine($"Not Found; Trying to get '{connectionStringName}' from environment variables...");
34+
Log.Debug("Not Found; Trying to get '{ConnectionStringName}' from environment variables...", connectionStringName);
3535
connectionString = Environment.GetEnvironmentVariable(connectionStringName);
3636
}
3737

3838
if (string.IsNullOrEmpty(connectionString))
3939
{
40-
Console.WriteLine($"Not Found; Trying to get '{connectionStringName}' from environment variables with prefix...");
40+
Log.Debug("Not Found; Trying to get '{ConnectionStringName}' from environment variables with prefix...", connectionStringName);
4141
connectionString = Environment.GetEnvironmentVariable($"CUSTOMCONNSTR_{connectionStringName}");
4242
}
4343

4444
// STILL NOT FOUND??!?!?
4545
if (string.IsNullOrEmpty(connectionString))
4646
{
47-
Console.WriteLine($"Connection string '{connectionStringName}' not found!");
47+
Log.Warning("Connection string '{ConnectionStringName}' not found!", connectionStringName);
4848
throw new ArgumentException($"Unable to find connection string '{connectionStringName}'");
4949
}
5050

Services/src/ThingsLibrary.Services/Extensions/Logger.cs

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,42 @@
55
// </copyright>
66
// ================================================================================
77

8-
namespace ThingsLibrary.Services.AspNetCore.Extensions
8+
namespace ThingsLibrary.Services.Extensions
99
{
1010
public static class LoggerExtensions
1111
{
12-
///// <summary>
13-
///// Initialize a long term logger
14-
///// </summary>
15-
//public static IServiceCollection AddSeriLogging(this IServiceCollection services, IConfiguration configuration)
16-
//{
17-
// // configure the logger as as possible
18-
// if (configuration.GetSection("Serilog").Exists())
19-
// {
20-
// Log.Logger = new LoggerConfiguration()
21-
// .ReadFrom.Configuration(configuration)
22-
// .CreateLogger();
23-
// }
24-
// else
25-
// {
26-
// Console.ForegroundColor = ConsoleColor.Red;
27-
// Console.WriteLine("WARNING: No 'serilog' section found in AppSettings.");
28-
// Console.ForegroundColor = ConsoleColor.Gray;
12+
/// <summary>
13+
/// Initialize a long term logger
14+
/// </summary>
15+
public static IServiceCollection AddSeriLogging(this IServiceCollection services, IConfiguration configuration)
16+
{
17+
// configure the logger as as possible
18+
if (configuration.GetSection("Serilog").Exists())
19+
{
20+
Log.Logger = new LoggerConfiguration()
21+
.ReadFrom.Configuration(configuration)
22+
.CreateLogger();
23+
}
24+
else
25+
{
26+
Console.ForegroundColor = ConsoleColor.Red;
27+
Console.WriteLine("WARNING: No 'serilog' section found in AppSettings.");
28+
Console.ForegroundColor = ConsoleColor.Gray;
2929

30-
// Log.Logger = new LoggerConfiguration()
31-
// .WriteTo.Console()
32-
// .CreateLogger();
30+
Log.Logger = new LoggerConfiguration()
31+
.WriteTo.Console()
32+
.CreateLogger();
3333

34-
// Log.Warning("Default Serilog Logger Initalized.");
35-
// }
34+
Log.Warning("Default Serilog Logger Initalized.");
35+
}
3636

37-
// // add the serilog
38-
// //services.AddSeriLogging(configuration);
39-
// //services.AddSerilog(Log.Logger);
40-
// //services.AddLogging(loggerBuilder => loggerBuilder.AddSerilog(Log.Logger));
37+
// add the serilog
38+
services.AddSeriLogging(configuration);
39+
services.AddSerilog(Log.Logger);
40+
services.AddLogging(loggerBuilder => loggerBuilder.AddSerilog(Log.Logger));
4141

42-
// // for chaining
43-
// return services;
44-
//}
42+
// for chaining
43+
return services;
44+
}
4545
}
4646
}

Services/src/ThingsLibrary.Services/Usings.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
// ================================================================================
3030
global using ThingsLibrary.DataType;
3131
global using ThingsLibrary.DataType.Extensions;
32-
global using ThingsLibrary.Services.AspNetCore.Extensions;
32+
global using ThingsLibrary.Services.Extensions;
3333

3434
global using ThingsLibrary.Schema.Library;
3535
global using ThingsLibrary.Schema.Library.Extensions;

0 commit comments

Comments
 (0)