Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NLogPublic

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
snakefoot wants to merge1 commit intoNLog:dev
base:dev
Choose a base branch
Loading
fromsnakefoot:config_targets_validate

Conversation

@snakefoot
Copy link
Contributor

No description provided.

@snakefootsnakefoot added the enhancementImprovement on existing feature labelNov 19, 2025
@coderabbitai
Copy link

coderabbitaibot commentedNov 19, 2025
edited
Loading

Walkthrough

Adds validation in the configuration parser to detect unrecognized attribute key/value pairs onrules andtargets 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 inParseRulesElement andParseTargetsElement, iterate any remainingValues 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
UpdatesInvalidNLogAttributeValues_shouldNotBreakLogging test XML to include unknown attributes (option="unknown" on<targets> andbingo="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 forrules andtargets 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 nameStatusExplanationResolution
Description check❓ InconclusiveNo 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 nameStatusExplanation
Title check✅ PassedThe 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✅ PassedNo 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 betweenf9c797c and173a9c0.

📒 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.

Theoption='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.

Thebingo='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 usingCodeRabbit! 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

@coderabbitaicoderabbitaibot 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 variabletargetsOptions is used within the rules validation context, which is confusing. Consider renaming it toruleOption,option, orruleAttribute 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 inLoggingConfigurationParser.cs.

Optional enhancement: Consider asserting that warnings about the unknown attributes (option='unknown' andbingo='tada') are logged to the InternalLogger, similar to howXmlConfig_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 betweena27d341 and77ab0dc.

📒 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.

@snakefootsnakefootforce-pushed theconfig_targets_validate branch 2 times, most recently fromcbe7b3d tof9c797cCompareNovember 22, 2025 10:11
Copy link

@coderabbitaicoderabbitaibot 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 whenthrowExceptions='true' orthrowConfigExceptions='true' is set.

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

Example test structure:

[Fact]publicvoidShouldThrowExceptionOnUnknownAttributeWhenOptionIsEnabledTest(){Assert.Throws<NLogConfigurationException>(()=>{newLogFactory().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>(()=>{newLogFactory().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 betweencbe7b3d andf9c797c.

📒 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 andbingo='tada' on rules) appropriately exercises the new parser validation feature in the no-throw scenario.

Also applies to: 207-207

@sonarqubecloud
Copy link

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

Assignees

No one assigned

Labels

enhancementImprovement on existing featuresize/S

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

1 participant

@snakefoot

[8]ページ先頭

©2009-2025 Movatter.jp