Skip to content

LoggingConfigurationParser - Report unrecognized options in targets and rules section#6045

Merged
snakefoot merged 1 commit intoNLog:devfrom
snakefoot:config_targets_validate
Jan 31, 2026
Merged

LoggingConfigurationParser - Report unrecognized options in targets and rules section#6045
snakefoot merged 1 commit intoNLog:devfrom
snakefoot:config_targets_validate

Conversation

@snakefoot
Copy link
Contributor

No description provided.

@snakefoot snakefoot added the enhancement Improvement on existing feature label Nov 19, 2025
@coderabbitai
Copy link

coderabbitai bot commented Nov 19, 2025

Walkthrough

Adds validation in the configuration parser to detect unrecognized attribute key/value pairs on rules and targets elements; when ThrowConfigExceptions/ThrowExceptions is enabled, leftover unknown attributes now cause configuration exceptions. A unit test was updated to include unknown attributes to exercise this behavior.

Changes

Cohort / File(s) Summary
Parser Validation Enhancement
src/NLog/Config/LoggingConfigurationParser.cs
After parsing known flags/values in ParseRulesElement and ParseTargetsElement, iterate any remaining Values and throw a configuration exception for unrecognized key/value pairs when throwing is enabled; adjusts rule insert-position handling before validation.
Test Case Update
tests/NLog.UnitTests/Config/XmlConfigTests.cs
Updates InvalidNLogAttributeValues_shouldNotBreakLogging test XML to include unknown attributes (option="unknown" on <targets> and bingo="tada" on <rules>) and renames the logger used in the test to match the test name.

Sequence Diagram

sequenceDiagram
    participant Loader as ConfigLoader
    participant Parser as LoggingConfigurationParser
    participant Element as Rules/Targets Element
    participant Validator as RemainingValuesChecker
    participant Error as ConfigException

    Loader->>Parser: Parse configuration XML
    Parser->>Element: Parse known attributes/flags (e.g., async, rule positions)
    Parser->>Validator: Inspect Element.Values for leftovers
    alt Throwing enabled and leftovers present
        Validator->>Error: Throw ConfigException for each unrecognized key/value
        Error-->>Parser: Exception propagated
        Parser-->>Loader: Parse fails
    else No leftovers or throwing disabled
        Validator-->>Parser: Validation OK / ignored
        Parser-->>Loader: Continue processing
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pay attention to:
    • Exact set of allowed attribute names for rules and targets parsing
    • Correct use of ThrowConfigExceptions / ThrowExceptions flags
    • Consistency of exception type/messages with existing config error handling
    • Updated unit test expecting either exception behavior or continued resilience

Poem

🐰
I hopped through XML, sniffed each name,
Found odd attributes — called them by name.
With whiskers twitching, I caught the clue,
"Unknown keys? Toss 'em!" — I shouted, true. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to evaluate whether it relates to the changeset. Add a description explaining the motivation, implementation details, and any testing performed for this validation enhancement.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding validation to report unrecognized options in targets and rules sections of the logging configuration parser.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f9c797c and 173a9c0.

📒 Files selected for processing (2)
  • src/NLog/Config/LoggingConfigurationParser.cs (2 hunks)
  • tests/NLog.UnitTests/Config/XmlConfigTests.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/NLog/Config/LoggingConfigurationParser.cs
🧰 Additional context used
🧬 Code graph analysis (1)
tests/NLog.UnitTests/Config/XmlConfigTests.cs (2)
src/NLog/LogFactory.cs (5)
  • LogFactory (53-1275)
  • LogFactory (123-126)
  • LogFactory (147-155)
  • LogFactory (424-429)
  • LogFactory (1042-1066)
src/NLog/Config/XmlLoggingConfiguration.cs (10)
  • XmlLoggingConfiguration (52-754)
  • XmlLoggingConfiguration (61-64)
  • XmlLoggingConfiguration (70-72)
  • XmlLoggingConfiguration (79-84)
  • XmlLoggingConfiguration (90-93)
  • XmlLoggingConfiguration (100-103)
  • XmlLoggingConfiguration (111-116)
  • XmlLoggingConfiguration (161-166)
  • XmlLoggingConfiguration (172-175)
  • XmlLoggingConfiguration (182-185)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: task-list-completed
🔇 Additional comments (3)
tests/NLog.UnitTests/Config/XmlConfigTests.cs (3)

204-204: LGTM! Tests unrecognized attribute handling on targets element.

The option='unknown' attribute correctly tests that unrecognized attributes on the <targets> element don't break logging when exception throwing is disabled.


207-207: LGTM! Tests unrecognized attribute handling on rules element.

The bingo='tada' attribute correctly tests that unrecognized attributes on the <rules> element don't break logging when exception throwing is disabled.


215-215: LGTM! Logger name now matches test method name.

Good update for clarity and consistency.


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: 0

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

550-558: Consider renaming variable for clarity.

The variable targetsOptions is used within the rules validation context, which is confusing. Consider renaming it to ruleOption, option, or ruleAttribute to better reflect its purpose.

Apply this diff:

         if (rulesElement.Values.Count > 0)
         {
-            foreach (var targetsOptions in rulesElement.Values)
+            foreach (var ruleOption in rulesElement.Values)
             {
-                var configException = new NLogConfigurationException($"Unrecognized value '{targetsOptions.Key}'='{targetsOptions.Value}' in section '{rulesElement.Name}'");
+                var configException = new NLogConfigurationException($"Unrecognized value '{ruleOption.Key}'='{ruleOption.Value}' in section '{rulesElement.Name}'");
                 if (MustThrowConfigException(configException))
                     throw configException;
             }
         }
tests/NLog.UnitTests/Config/XmlConfigTests.cs (1)

197-223: Good test coverage for graceful degradation.

The test appropriately validates that unknown attributes on <targets> and <rules> elements don't break logging functionality when exception throwing is disabled. This aligns well with the new validation logic in LoggingConfigurationParser.cs.

Optional enhancement: Consider asserting that warnings about the unknown attributes (option='unknown' and bingo='tada') are logged to the InternalLogger, similar to how XmlConfig_attributes_shouldNotLogWarningsToInternalLog captures internal log output. This would provide more complete validation that the configuration parser properly detects and reports these issues.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a27d341 and 77ab0dc.

📒 Files selected for processing (2)
  • src/NLog/Config/LoggingConfigurationParser.cs (2 hunks)
  • tests/NLog.UnitTests/Config/XmlConfigTests.cs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/NLog/Config/LoggingConfigurationParser.cs (1)
src/NLog/NLogConfigurationException.cs (4)
  • NLogConfigurationException (51-53)
  • NLogConfigurationException (59-62)
  • NLogConfigurationException (98-101)
  • NLogConfigurationException (115-118)
🔇 Additional comments (1)
src/NLog/Config/LoggingConfigurationParser.cs (1)

856-867: LGTM!

The validation logic correctly identifies and rejects unrecognized attributes in the targets section while properly excluding the allowed "async" attribute from validation.

@snakefoot snakefoot force-pushed the config_targets_validate branch 2 times, most recently from cbe7b3d to f9c797c Compare November 22, 2025 10:11
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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/NLog.UnitTests/Config/XmlConfigTests.cs (1)

215-215: Fix the logger name to match the test method.

The logger name "InvalidInternalLogLevel_shouldNotBreakLogging" doesn't match the test method name "InvalidNLogAttributeValues_shouldNotBreakLogging", likely from a copy-paste oversight.

Apply this diff:

-                var logger = logFactory.GetLogger("InvalidInternalLogLevel_shouldNotBreakLogging");
+                var logger = logFactory.GetLogger("InvalidNLogAttributeValues_shouldNotBreakLogging");
🧹 Nitpick comments (1)
tests/NLog.UnitTests/Config/XmlConfigTests.cs (1)

197-223: Consider adding test coverage for the exception-throwing scenario.

The current test validates that unknown attributes don't break logging when exceptions are suppressed. However, there's no corresponding test that verifies exceptions ARE thrown when throwExceptions='true' or throwConfigExceptions='true' is set.

Following the pattern of ShoudThrowExceptionOnDuplicateAttributeWhenOptionIsEnabledTest (line 433), consider adding a similar test for unknown attributes on targets and rules elements.

Example test structure:

[Fact]
public void ShouldThrowExceptionOnUnknownAttributeWhenOptionIsEnabledTest()
{
    Assert.Throws<NLogConfigurationException>(() =>
    {
        new LogFactory().Setup().LoadConfigurationFromXml(@"
        <nlog throwExceptions='true'>
            <targets option='unknown'>
                <target name='debug' type='Debug' layout='${message}' />
            </targets>
            <rules>
                <logger name='*' minlevel='info' appendto='debug' />
            </rules>
        </nlog>");
    });

    Assert.Throws<NLogConfigurationException>(() =>
    {
        new LogFactory().Setup().LoadConfigurationFromXml(@"
        <nlog throwConfigExceptions='true'>
            <targets>
                <target name='debug' type='Debug' layout='${message}' />
            </targets>
            <rules bingo='tada'>
                <logger name='*' minlevel='info' appendto='debug' />
            </rules>
        </nlog>");
    });
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cbe7b3d and f9c797c.

📒 Files selected for processing (2)
  • src/NLog/Config/LoggingConfigurationParser.cs (2 hunks)
  • tests/NLog.UnitTests/Config/XmlConfigTests.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/NLog/Config/LoggingConfigurationParser.cs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: task-list-completed
🔇 Additional comments (1)
tests/NLog.UnitTests/Config/XmlConfigTests.cs (1)

204-204: LGTM! Good test coverage for unknown attribute validation.

The addition of unknown attributes (option='unknown' on targets and bingo='tada' on rules) appropriately exercises the new parser validation feature in the no-throw scenario.

Also applies to: 207-207

@snakefoot snakefoot force-pushed the config_targets_validate branch from f9c797c to 173a9c0 Compare November 22, 2025 10:24
@sonarqubecloud
Copy link

@snakefoot snakefoot merged commit b1f44e6 into NLog:dev Jan 31, 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

enhancement Improvement on existing feature size/S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant