Skip to content

LoggingConfigurationFileLoader - Handle unknown type loading for App.config#6072

Merged
snakefoot merged 1 commit intoNLog:devfrom
snakefoot:appconfig_loader
Jan 3, 2026
Merged

LoggingConfigurationFileLoader - Handle unknown type loading for App.config#6072
snakefoot merged 1 commit intoNLog:devfrom
snakefoot:appconfig_loader

Conversation

@snakefoot
Copy link
Contributor

@snakefoot snakefoot commented Jan 3, 2026

Improve type-load-exception-handling if by accident using NetFramework DLL on NetStandard/NetCore-target.

Similar to what is done for AppEnvironmentWrapper in Safe-methods.

@coderabbitai
Copy link

coderabbitai bot commented Jan 3, 2026

Walkthrough

The changes refactor NLog's App.config loading mechanism by introducing a new NETFRAMEWORK-specific helper method TryLoadFromAppConfig, restricting the AppConfig property from public to internal visibility, simplifying its error handling, and centralizing configuration loading error handling with standardized logging.

Changes

Cohort / File(s) Summary
Configuration Access Control
src/NLog/Config/ConfigSectionHandler.cs
Visibility of AppConfig property changed from public to internal; exception handling and logging removed from getter, simplifying direct retrieval logic.
Configuration Loading Error Handling
src/NLog/Config/LoggingConfigurationFileLoader.cs
Added NETFRAMEWORK-specific TryLoadFromAppConfig() helper method with robust exception handling and conditional rethrow logic; added FailedToLoadFromAppConfigMessage constant; updated configuration loading to use new helper instead of direct property access.
Code Cleanup
src/NLog/LogFactory.cs
Removed TODO comment from LoadConfiguration() method.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hops of joy through the config maze,
Error handling now ablaze,
App.config finds its cozy place,
In TryLoad's safe and guarded space—
No more public, internal's the way,
Better logging saves the day! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive The pull request lacks any description provided by the author, making it impossible to verify that author intent is captured. Please add a description explaining the motivation, specific changes, and any relevant context for the exception handling improvements.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: making LoggingConfigurationFileLoader handle App.config loading more robustly with better exception handling and a new helper method.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/NLog/Config/LoggingConfigurationFileLoader.cs (1)

93-116: Method naming doesn't follow TryParse pattern.

The method name TryLoadFromAppConfig suggests the TryParse pattern (returns null on failure, doesn't throw exceptions except fatal ones). However, this method throws exceptions conditionally on lines 104, 110, and 113, which violates that pattern and may confuse maintainers.

Consider either:

  • Option A: Rename to LoadFromAppConfig to indicate it can throw
  • Option B: Refactor to never throw (return null on all errors) and remove the outer try/catch in Load
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 218aa12 and fdfcb6c.

📒 Files selected for processing (3)
  • src/NLog/Config/ConfigSectionHandler.cs
  • src/NLog/Config/LoggingConfigurationFileLoader.cs
  • src/NLog/LogFactory.cs
💤 Files with no reviewable changes (1)
  • src/NLog/LogFactory.cs
🧰 Additional context used
🧬 Code graph analysis (1)
src/NLog/Config/ConfigSectionHandler.cs (1)
src/NLog/Config/LoggingConfigurationFileLoader.cs (5)
  • LoggingConfiguration (56-91)
  • LoggingConfiguration (94-116)
  • LoggingConfiguration (121-133)
  • LoggingConfiguration (172-194)
  • LoggingConfiguration (196-199)
🔇 Additional comments (2)
src/NLog/Config/LoggingConfigurationFileLoader.cs (1)

118-118: Good practice: Centralized error message.

The constant FailedToLoadFromAppConfigMessage promotes consistency in error reporting across the configuration loading paths.

src/NLog/Config/ConfigSectionHandler.cs (1)

60-67: AppConfig property is already internal with proper error handling delegation.

The AppConfig property is currently marked as internal static, and verification confirms there are no external code references to this property outside the NLog library (search returned no matches outside src/NLog/**). The only internal usage is in LoggingConfigurationFileLoader.cs:98 within the TryLoadFromAppConfig method, which properly wraps the call with comprehensive error handling (lines 94-116). Exception handling includes separate catches for NLogConfigurationException and general Exception types, with appropriate logging via InternalLogger and conditional re-throwing based on ThrowExceptions and ThrowConfigExceptions flags. The simplified getter using the as cast operator is appropriate design since error handling is properly delegated to the caller.

Comment on lines +61 to +77
try
{
var appConfig = TryLoadFromAppConfig(logFactory);
if (appConfig != null)
return appConfig;
}
catch (NLogConfigurationException)
{
throw;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately() || logFactory.ThrowExceptions || LogManager.ThrowExceptions)
throw;

InternalLogger.Error(ex, FailedToLoadFromAppConfigMessage); // NetStandard does not support .NET Framework types
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Redundant error handling creates dead code.

The try/catch block wrapping TryLoadFromAppConfig appears redundant because TryLoadFromAppConfig already implements comprehensive exception handling (lines 96-116).

The condition on lines 73-74 is identical to the condition on lines 109-110 in TryLoadFromAppConfig. This means:

  • When TryLoadFromAppConfig throws from line 110, the condition was true
  • Load catches it and evaluates the same condition (lines 73-74), which must also be true
  • Therefore, line 76 (the error logging) is unreachable dead code

Additionally, the catch-and-rethrow of NLogConfigurationException (lines 67-70) serves no purpose.

🔎 Proposed fix: Remove redundant outer try/catch
 #if NETFRAMEWORK
             if (string.IsNullOrEmpty(filename))
             {
-                try
-                {
-                    var appConfig = TryLoadFromAppConfig(logFactory);
-                    if (appConfig != null)
-                        return appConfig;
-                }
-                catch (NLogConfigurationException)
-                {
-                    throw;
-                }
-                catch (Exception ex)
-                {
-                    if (ex.MustBeRethrownImmediately() || logFactory.ThrowExceptions || LogManager.ThrowExceptions)
-                        throw;
-
-                    InternalLogger.Error(ex, FailedToLoadFromAppConfigMessage); // NetStandard does not support .NET Framework types
-                }
+                var appConfig = TryLoadFromAppConfig(logFactory);
+                if (appConfig != null)
+                    return appConfig;
             }
 #endif
🤖 Prompt for AI Agents
In src/NLog/Config/LoggingConfigurationFileLoader.cs around lines 61 to 77, the
outer try/catch around TryLoadFromAppConfig is redundant and creates dead code
because TryLoadFromAppConfig already handles and rethrows exceptions
appropriately; remove the entire outer try/catch (including the
NLogConfigurationException catch and the general Exception catch that logs
FailedToLoadFromAppConfigMessage) and replace it with a simple call that returns
the result if non-null, allowing TryLoadFromAppConfig to perform its own
exception logic and rethrowing as designed.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 3, 2026

@snakefoot snakefoot changed the title LoggingConfigurationFileLoader - Handle unknown type loading exceptions LoggingConfigurationFileLoader - Handle unknown type loading for App.config Jan 3, 2026
@snakefoot snakefoot merged commit fba8395 into NLog:dev Jan 3, 2026
5 of 6 checks passed
@snakefoot snakefoot added this to the 6.1.0 milestone Jan 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant