Skip to content

Commit 7696013

Browse files
authored
Structured logging refactor (#1594)
This is a bit of the work for #1517, focusing on a just the CLI project.
1 parent ebe4ef4 commit 7696013

6 files changed

Lines changed: 52 additions & 48 deletions

File tree

src/Cli/Commands/AddOptions.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public AddOptions(
5858

5959
public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
6060
{
61-
logger.LogInformation($"{PRODUCT_NAME} {ProductInfo.GetProductVersion()}");
61+
logger.LogInformation("{productName} {version}", PRODUCT_NAME, ProductInfo.GetProductVersion());
6262
if (!IsEntityProvided(Entity, logger, command: "add"))
6363
{
6464
return;
@@ -67,12 +67,12 @@ public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileS
6767
bool isSuccess = ConfigGenerator.TryAddEntityToConfigWithOptions(this, loader, fileSystem);
6868
if (isSuccess)
6969
{
70-
logger.LogInformation($"Added new entity: {Entity} with source: {Source} and permissions: {string.Join(SEPARATOR, Permissions.ToArray())}.");
71-
logger.LogInformation($"SUGGESTION: Use 'dab update [entity-name] [options]' to update any entities in your config.");
70+
logger.LogInformation("Added new entity: {Entity} with source: {Source} and permissions: {permissions}.", Entity, Source, string.Join(SEPARATOR, Permissions));
71+
logger.LogInformation("SUGGESTION: Use 'dab update [entity-name] [options]' to update any entities in your config.");
7272
}
7373
else
7474
{
75-
logger.LogError($"Could not add entity: {Entity} with source: {Source} and permissions: {string.Join(SEPARATOR, Permissions.ToArray())}.");
75+
logger.LogError("Could not add entity: {Entity} with source: {Source} and permissions: {permissions}.", Entity, Source, string.Join(SEPARATOR, Permissions));
7676
}
7777
}
7878
}

src/Cli/Commands/InitOptions.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,16 +105,16 @@ public InitOptions(
105105

106106
public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
107107
{
108-
logger.LogInformation($"{PRODUCT_NAME} {ProductInfo.GetProductVersion()}");
108+
logger.LogInformation("{productName} {version}", PRODUCT_NAME, ProductInfo.GetProductVersion());
109109
bool isSuccess = ConfigGenerator.TryGenerateConfig(this, loader, fileSystem);
110110
if (isSuccess)
111111
{
112-
logger.LogInformation($"Config file generated.");
113-
logger.LogInformation($"SUGGESTION: Use 'dab add [entity-name] [options]' to add new entities in your config.");
112+
logger.LogInformation("Config file generated.");
113+
logger.LogInformation("SUGGESTION: Use 'dab add [entity-name] [options]' to add new entities in your config.");
114114
}
115115
else
116116
{
117-
logger.LogError($"Could not generate config file.");
117+
logger.LogError("Could not generate config file.");
118118
}
119119
}
120120
}

src/Cli/Commands/StartOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public StartOptions(bool verbose, LogLevel? logLevel, bool isHttpsRedirectionDis
3737

3838
public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
3939
{
40-
logger.LogInformation($"{PRODUCT_NAME} {ProductInfo.GetProductVersion()}");
40+
logger.LogInformation("{productName} {version}", PRODUCT_NAME, ProductInfo.GetProductVersion());
4141
bool isSuccess = ConfigGenerator.TryStartEngineWithOptions(this, loader, fileSystem);
4242

4343
if (!isSuccess)

src/Cli/Commands/UpdateOptions.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public UpdateOptions(
9898

9999
public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
100100
{
101-
logger.LogInformation($"{PRODUCT_NAME} {ProductInfo.GetProductVersion()}");
101+
logger.LogInformation("{productName} {version}", PRODUCT_NAME, ProductInfo.GetProductVersion());
102102
if (!IsEntityProvided(Entity, logger, command: "update"))
103103
{
104104
return;
@@ -108,11 +108,11 @@ public void Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileS
108108

109109
if (isSuccess)
110110
{
111-
logger.LogInformation($"Updated the entity: {Entity}.");
111+
logger.LogInformation("Updated the entity: {Entity}.", Entity);
112112
}
113113
else
114114
{
115-
logger.LogError($"Could not update the entity: {Entity}.");
115+
logger.LogError("Could not update the entity: {Entity}.", Entity);
116116
}
117117
}
118118
}

src/Cli/ConfigGenerator.cs

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -105,13 +105,13 @@ public static bool TryCreateRuntimeConfig(InitOptions options, FileSystemRuntime
105105
string? graphQLSchemaPath = options.GraphQLSchemaPath;
106106
if (string.IsNullOrEmpty(cosmosDatabase) || string.IsNullOrEmpty(graphQLSchemaPath))
107107
{
108-
_logger.LogError($"Missing mandatory configuration option for CosmosDB_NoSql: --cosmosdb_nosql-database, and --graphql-schema");
108+
_logger.LogError("Missing mandatory configuration option for CosmosDB_NoSql: --cosmosdb_nosql-database, and --graphql-schema");
109109
return false;
110110
}
111111

112112
if (!fileSystem.File.Exists(graphQLSchemaPath))
113113
{
114-
_logger.LogError($"GraphQL Schema File: {graphQLSchemaPath} not found.");
114+
_logger.LogError("GraphQL Schema File: {graphQLSchemaPath} not found.", graphQLSchemaPath);
115115
return false;
116116
}
117117

@@ -151,34 +151,34 @@ public static bool TryCreateRuntimeConfig(InitOptions options, FileSystemRuntime
151151

152152
if (!IsURIComponentValid(restPath))
153153
{
154-
_logger.LogError($"{ApiType.REST} path {RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG}");
154+
_logger.LogError("{apiType} path {message}", ApiType.REST, RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG);
155155
return false;
156156
}
157157

158158
if (!IsURIComponentValid(options.GraphQLPath))
159159
{
160-
_logger.LogError($"{ApiType.GraphQL} path {RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG}");
160+
_logger.LogError("{apiType} path {message}", ApiType.GraphQL, RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG);
161161
return false;
162162
}
163163

164164
if (!IsURIComponentValid(runtimeBaseRoute))
165165
{
166-
_logger.LogError($"Runtime base-route {RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG}");
166+
_logger.LogError("Runtime base-route {message}", RuntimeConfigValidator.URI_COMPONENT_WITH_RESERVED_CHARS_ERR_MSG);
167167
return false;
168168
}
169169

170170
if (runtimeBaseRoute is not null)
171171
{
172172
if (!Enum.TryParse(options.AuthenticationProvider, ignoreCase: true, out EasyAuthType easyAuthMode) || easyAuthMode is not EasyAuthType.StaticWebApps)
173173
{
174-
_logger.LogError($"Runtime base-route can only be specified when the authentication provider is Static Web Apps.");
174+
_logger.LogError("Runtime base-route can only be specified when the authentication provider is Static Web Apps.");
175175
return false;
176176
}
177177
}
178178

179179
if (options.RestDisabled && options.GraphQLDisabled)
180180
{
181-
_logger.LogError($"Both Rest and GraphQL cannot be disabled together.");
181+
_logger.LogError("Both Rest and GraphQL cannot be disabled together.");
182182
return false;
183183
}
184184

@@ -234,7 +234,7 @@ public static bool TryAddEntityToConfigWithOptions(AddOptions options, FileSyste
234234

235235
if (!loader.TryLoadConfig(runtimeConfigFile, out RuntimeConfig? runtimeConfig))
236236
{
237-
_logger.LogError($"Failed to read the config file: {runtimeConfigFile}.");
237+
_logger.LogError("Failed to read the config file: {runtimeConfigFile}.", runtimeConfigFile);
238238
return false;
239239
}
240240

@@ -262,7 +262,7 @@ public static bool TryAddNewEntity(AddOptions options, RuntimeConfig initialRunt
262262
//
263263
if (initialRuntimeConfig.Entities.ContainsKey(options.Entity))
264264
{
265-
_logger.LogWarning($"Entity-{options.Entity} is already present. No new changes are added to Config.");
265+
_logger.LogWarning("Entity '{entityName}' is already present. No new changes are added to Config.", options.Entity);
266266
return false;
267267
}
268268

@@ -433,7 +433,7 @@ public static bool TryCreateSourceObjectForNewEntity(
433433
string? role, operations;
434434
if (!TryGetRoleAndOperationFromPermission(permissions, out role, out operations))
435435
{
436-
_logger.LogError($"Failed to fetch the role and operation from the given permission string: {string.Join(SEPARATOR, permissions.ToArray())}.");
436+
_logger.LogError("Failed to fetch the role and operation from the given permission string: {permissions}.", string.Join(SEPARATOR, permissions));
437437
return null;
438438
}
439439

@@ -470,7 +470,7 @@ public static bool TryUpdateEntityWithOptions(UpdateOptions options, FileSystemR
470470

471471
if (!TryUpdateExistingEntity(options, runtimeConfig, out RuntimeConfig updatedConfig))
472472
{
473-
_logger.LogError($"Failed to update the Entity: {options.Entity}.");
473+
_logger.LogError("Failed to update the Entity: {entityName}.", options.Entity);
474474
return false;
475475
}
476476

@@ -489,9 +489,9 @@ public static bool TryUpdateExistingEntity(UpdateOptions options, RuntimeConfig
489489
{
490490
updatedConfig = initialConfig;
491491
// Check if Entity is present
492-
if (!initialConfig.Entities.TryGetValue(options.Entity!, out Entity? entity))
492+
if (!initialConfig.Entities.TryGetValue(options.Entity, out Entity? entity))
493493
{
494-
_logger.LogError($"Entity:{options.Entity} not found. Please add the entity first.");
494+
_logger.LogError("Entity: '{entityName}' not found. Please add the entity first.", options.Entity);
495495
return false;
496496
}
497497

@@ -557,7 +557,7 @@ public static bool TryUpdateExistingEntity(UpdateOptions options, RuntimeConfig
557557

558558
if (updatedPermissions is null)
559559
{
560-
_logger.LogError($"Failed to update permissions.");
560+
_logger.LogError("Failed to update permissions.");
561561
return false;
562562
}
563563
}
@@ -567,13 +567,13 @@ public static bool TryUpdateExistingEntity(UpdateOptions options, RuntimeConfig
567567
if (options.FieldsToInclude is not null && options.FieldsToInclude.Any()
568568
|| options.FieldsToExclude is not null && options.FieldsToExclude.Any())
569569
{
570-
_logger.LogInformation($"--permissions is mandatory with --fields.include and --fields.exclude.");
570+
_logger.LogInformation("--permissions is mandatory with --fields.include and --fields.exclude.");
571571
return false;
572572
}
573573

574574
if (options.PolicyRequest is not null || options.PolicyDatabase is not null)
575575
{
576-
_logger.LogInformation($"--permissions is mandatory with --policy-request and --policy-database.");
576+
_logger.LogInformation("--permissions is mandatory with --policy-request and --policy-database.");
577577
return false;
578578
}
579579

@@ -793,9 +793,10 @@ private static bool TryGetUpdatedSourceObjectWithOptions(
793793

794794
if (IsStoredProcedureConvertedToOtherTypes(entity, options) || IsEntityBeingConvertedToStoredProcedure(entity, options))
795795
{
796-
_logger.LogWarning($"Stored procedures can be configured only with {EntityActionOperation.Execute} action whereas tables/views are configured with CRUD actions. Update the actions configured for all the roles for this entity.");
796+
_logger.LogWarning(
797+
"Stored procedures can be configured only with '{storedProcedureAction}' action whereas tables/views are configured with CRUD actions. Update the actions configured for all the roles for this entity.",
798+
EntityActionOperation.Execute);
797799
}
798-
799800
}
800801

801802
// No need to validate parameter and key field usage when there are no changes to the source object defined in 'options'
@@ -883,22 +884,22 @@ public static bool VerifyCanUpdateRelationship(RuntimeConfig runtimeConfig, stri
883884
// Both the source entity and target entity needs to present in config to establish relationship.
884885
if (!runtimeConfig.Entities.ContainsKey(targetEntity))
885886
{
886-
_logger.LogError($"Entity:{targetEntity} is not present. Relationship cannot be added.");
887+
_logger.LogError("Entity: '{targetEntity}' is not present. Relationship cannot be added.", targetEntity);
887888
return false;
888889
}
889890

890891
// Check if provided value of cardinality is present in the enum.
891892
if (!string.Equals(cardinality, Cardinality.One.ToString(), StringComparison.OrdinalIgnoreCase)
892893
&& !string.Equals(cardinality, Cardinality.Many.ToString(), StringComparison.OrdinalIgnoreCase))
893894
{
894-
_logger.LogError($"Failed to parse the given cardinality : {cardinality}. Supported values are one/many.");
895+
_logger.LogError("Failed to parse the given cardinality :'{cardinality}'. Supported values are 'one' or 'many'.", cardinality);
895896
return false;
896897
}
897898

898899
// If GraphQL is disabled, entity cannot be used in relationship
899900
if (!runtimeConfig.Entities[targetEntity].GraphQL.Enabled)
900901
{
901-
_logger.LogError($"Entity: {targetEntity} cannot be used in relationship as it is disabled for GraphQL.");
902+
_logger.LogError("Entity: '{targetEntity}' cannot be used in relationship as it is disabled for GraphQL.", targetEntity);
902903
return false;
903904
}
904905

@@ -948,15 +949,15 @@ public static bool VerifyCanUpdateRelationship(RuntimeConfig runtimeConfig, stri
948949
/// It will use the config provided by the user, else based on the environment value
949950
/// it will either merge the config if base config and environmentConfig is present
950951
/// else it will choose a single config based on precedence (left to right) of
951-
/// overrides < environmentConfig < defaultConfig
952+
/// overrides &lt; environmentConfig &lt; defaultConfig
952953
/// Also preforms validation to check connection string is not null or empty.
953954
/// </summary>
954955
public static bool TryStartEngineWithOptions(StartOptions options, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
955956
{
956957
string? configToBeUsed = options.Config;
957958
if (string.IsNullOrEmpty(configToBeUsed) && ConfigMerger.TryMergeConfigsIfAvailable(fileSystem, loader, _logger, out configToBeUsed))
958959
{
959-
_logger.LogInformation($"Using merged config file based on environment:{configToBeUsed}.");
960+
_logger.LogInformation("Using merged config file based on environment: {configToBeUsed}.", configToBeUsed);
960961
}
961962

962963
if (!TryGetConfigFileBasedOnCliPrecedence(loader, configToBeUsed, out string runtimeConfigFile))
@@ -976,7 +977,7 @@ public static bool TryStartEngineWithOptions(StartOptions options, FileSystemRun
976977

977978
if (string.IsNullOrWhiteSpace(deserializedRuntimeConfig.DataSource.ConnectionString))
978979
{
979-
_logger.LogError($"Invalid connection-string provided in the config.");
980+
_logger.LogError("Invalid connection-string provided in the config.");
980981
return false;
981982
}
982983

@@ -991,20 +992,21 @@ public static bool TryStartEngineWithOptions(StartOptions options, FileSystemRun
991992
{
992993
if (options.LogLevel is < LogLevel.Trace or > LogLevel.None)
993994
{
994-
_logger.LogError($"LogLevel's valid range is 0 to 6, your value: {options.LogLevel}, see: " +
995-
$"https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel?view=dotnet-plat-ext-7.0");
995+
_logger.LogError(
996+
"LogLevel's valid range is 0 to 6, your value: {logLevel}, see: https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.loglevel?view=dotnet-plat-ext-6.0",
997+
options.LogLevel);
996998
return false;
997999
}
9981000

9991001
minimumLogLevel = (LogLevel)options.LogLevel;
1000-
_logger.LogInformation($"Setting minimum LogLevel: {minimumLogLevel}.");
1002+
_logger.LogInformation("Setting minimum LogLevel: {minimumLogLevel}.", minimumLogLevel);
10011003
}
10021004
else
10031005
{
10041006
minimumLogLevel = Startup.GetLogLevelBasedOnMode(deserializedRuntimeConfig);
10051007
HostMode hostModeType = deserializedRuntimeConfig.Runtime.Host.Mode;
10061008

1007-
_logger.LogInformation($"Setting default minimum LogLevel: {minimumLogLevel} for {hostModeType} mode.");
1009+
_logger.LogInformation("Setting default minimum LogLevel: {minimumLogLevel} for {hostMode} mode.", minimumLogLevel, hostModeType);
10081010
}
10091011

10101012
args.Add("--LogLevel");

0 commit comments

Comments
 (0)