Skip to content

Log4JXmlEventLayout using Nlog XmlLayout#5774

Merged
snakefoot merged 16 commits intoNLog:devfrom
ana1250:dev
Apr 26, 2025
Merged

Log4JXmlEventLayout using Nlog XmlLayout#5774
snakefoot merged 16 commits intoNLog:devfrom
ana1250:dev

Conversation

@ana1250
Copy link
Contributor

@ana1250 ana1250 commented Apr 12, 2025

This PR replaces the usage of System.Xml with NLog’s native XML layout infrastructure (XmlLayout, XmlElement, etc.) to construct Log4j-compatible XML logs. #5747

System.Xml Removal: Removed System.Xml dependencies from both the Log4JXmlLayout and Log4JXmlEventLayoutParameter classes.

Renderer Updates:

  • Removed the Log4jRenderer and mapped Chainsaw logs to use the new layout.
  • Updated Log4JXmlEventLayout with improved rendering logic and formatting.

New Features:

  • Added CDataEncode property to optionally wrap values in CDATA.
  • Introduced RemoveInvalidXmlChar to strip out illegal XML characters.
  • Added ThrowableEncode for escaping stack trace output. -- Removed as per review

Tests:

  • Added tests for CDATA encoding and invalid character removal.
  • Fixed and updated existing tests (Log4JXmlEventLayoutParameter spacing issue).
  • Marked outdated bad XML test as obsolete.
  • Temporarily modified layout tests for ongoing validation.
  • Fixed the appinfo switch case

TODO:

Fix Scopenested rendering
Remove XML helper from Network.Target and dependent obsolete unit test

ana1250 and others added 6 commits April 12, 2025 13:17
Mapped the Chainsaw to log4j layout
Removed depenecy of log4j paramter class from System.xml
Removed depenecy of log4j layoutclass from System.xml
Fixed unit test for log4j paramter (had extra space).
Added Cdata property in XmlElement class.
Temp Unit test log4jxmllayout tests change
Added Invalid Xml Character Remover
Abstarcted logic of inner renderer into xml helper methods.
Added tests for cdata
Marked Previous test case for bad xml as obsolete
Added new unit test for invalid xml values.
Updated Log4JXmlEventLayout to improve XML formatting and rendering. Key changes include:
- Added `ThrowableEncode` property for XML escaping control.
- Simplified `ScopeNestedSeparator` handling.
- Renamed `WrapInCData` to `CDataEncode`.
- Removed deprecated methods from `XmlHelper`.
- Updated test suite with new tests and removed obsolete ones.
[WIP] Log4JXmlEventLayout using XmlLayout
@welcome
Copy link

welcome bot commented Apr 12, 2025

Thanks for opening this pull request!
We will try to review this soon! Please note that pull requests with unit tests are earlier accepted 👼

@coderabbitai
Copy link

coderabbitai bot commented Apr 12, 2025

Walkthrough

This pull request refactors the XML layout rendering for Log4j events by removing the dedicated Log4JXmlEventLayoutRenderer class and integrating its functionality directly into the Log4JXmlEventLayout class via a new InnerXml property. The layout now explicitly builds the XML structure in the overridden InitializeLayout method. Several properties in both the layout and the ChainsawTarget class were updated to replace references from the removed renderer to the new layout instance. Helper methods were added to sanitize XML content and safely handle CDATA sections. Tests were updated to reflect these changes and to add coverage for CDATA wrapping, nested scopes, and invalid XML character removal.

Changes

File(s) Change Summary
src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs Removed constructor and Renderer dependency; added InnerXml property and InitializeLayout method to build XML structure; updated many properties to remove renderer delegation and use backing fields; added WriteThrowableCData and other new properties; updated message rendering methods to use InnerXml.
src/NLog.Targets.Network/Layouts/Log4JXmlEventLayoutRenderer.cs Entire file removed, deleting the legacy Log4j XML layout renderer class and its logic.
src/NLog.Targets.Network/Layouts/Log4JXmlEventParameter.cs Modified Name property setter to assign value directly without removing invalid XML characters.
src/NLog.Targets.Network/Targets/ChainsawTarget.cs Replaced all references to the removed Renderer property with _log4JLayout for various properties controlling XML layout behavior.
src/NLog/Config/ConfigurationItemFactory.cs Removed registration of the "log4jxmlevent" layout renderer type from the layout renderer factory.
src/NLog/Internal/XmlHelper.cs Added three public static methods: RemoveInvalidXmlIfNeeded, EscapeCDataIfNeeded, and WrapInCData to sanitize XML strings and safely handle CDATA sections.
src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs Added CDataEncode boolean property; updated rendering logic to optionally wrap output in CDATA and remove invalid XML characters accordingly.
src/NLog/Layouts/XML/XmlElement.cs Added CDataEncode property to control whether element content is wrapped in CDATA instead of escaped.
tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs Updated tests to remove usage of the old renderer; restructured XML layout configuration; added tests for CDATA wrapping of exceptions, nested scope inclusion, invalid XML character removal, and exception encoding behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Logger
    participant ChainsawTarget
    participant Layout as Log4JXmlEventLayout
    participant InnerXml as XmlLayout
    participant Encoder as XmlEncodeLayoutRendererWrapper
    participant Helper as XmlHelper

    Logger->>ChainsawTarget: Send log event
    ChainsawTarget->>Layout: Process event
    Layout->>InnerXml: Build XML structure
    InnerXml->>Encoder: Render XML elements
    Encoder->>Helper: Check config (RemoveInvalidXmlIfNeeded / EscapeCDataIfNeeded)
    Helper-->>Encoder: Return sanitized XML
    Encoder-->>InnerXml: Return final XML output
    InnerXml-->>Layout: Provide rendered XML
    Layout-->>ChainsawTarget: Return formatted log output
Loading

Poem

In a field of code where logs abound,
I hop and skip with joyful sound.
New XML paths shine, both neat and bright,
With CDATA magic and helpers in sight.
I’m a rabbit of change, dancing on the floor,
Celebrating tweaks that make logging soar!
🐇 Happy hopping in the land of code galore!


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Nitpick comments (2)
src/NLog/Layouts/XML/XmlElement.cs (1)

109-116: Consider renaming property for consistency.
This property is named RemoveInvalidXmlChar (singular), while related methods are plural (RemoveInvalidXmlChars). Renaming it to RemoveInvalidXmlChars could reduce confusion.

Proposed diff:

- public bool RemoveInvalidXmlChar
+ public bool RemoveInvalidXmlChars
src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs (1)

65-69: Fix the minor typo in the XML-doc comment.

The summary line says "Remove Imvalid Xml Characters" instead of "Remove Invalid Xml Characters."

-/// Remove Imvalid Xml Characters from inner
+/// Remove Invalid Xml Characters from inner
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8fa0ef and c4a04bb.

📒 Files selected for processing (9)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (3 hunks)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventLayoutRenderer.cs (0 hunks)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventParameter.cs (1 hunks)
  • src/NLog.Targets.Network/Targets/ChainsawTarget.cs (11 hunks)
  • src/NLog/Config/ConfigurationItemFactory.cs (0 hunks)
  • src/NLog/Internal/XmlHelper.cs (1 hunks)
  • src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs (3 hunks)
  • src/NLog/Layouts/XML/XmlElement.cs (1 hunks)
  • tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs (7 hunks)
💤 Files with no reviewable changes (2)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventLayoutRenderer.cs
  • src/NLog/Config/ConfigurationItemFactory.cs
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs (2)
src/NLog/ScopeContext.cs (1)
  • ScopeContext (52-887)
src/NLog/Internal/ScopeContextAsyncState.cs (1)
  • PushNestedState (250-263)
src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (1)
src/NLog.Targets.Network/Layouts/Log4JXmlEventParameter.cs (1)
  • Log4JXmlEventParameter (48-50)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: WIP
  • GitHub Check: WIP
🔇 Additional comments (22)
src/NLog.Targets.Network/Layouts/Log4JXmlEventParameter.cs (1)

57-57: Validate intentional removal of XML sanitization.
Previously, assigning Name sanitized invalid XML characters. Now, invalid characters can slip through, potentially causing malformed XML. Please confirm if you intend to remove sanitization or reintroduce it for safety.

If reintroducing is desired, consider this quick fix:

- public string Name { get => _name; set => _name = value; }
+ public string Name { get => _name; set => _name = XmlHelper.RemoveInvalidXmlChars(value); }
src/NLog/Layouts/XML/XmlElement.cs (1)

99-107: Prevent potential conflicts between Encode and CDataEncode.
When both Encode and CDataEncode are enabled, it might lead to double-escape or unexpected output. Please verify whether these properties should be mutually exclusive or if the current logic handles both safely.

src/NLog/Internal/XmlHelper.cs (1)

449-454: Check for valid orgLength before trimming and appending.
If orgLength is out of range, ToString(orgLength, ...) may throw an exception. Consider adding boundary checks to prevent potential errors.

src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs (3)

60-64: Add a new property for CDATA encoding.

Introducing the CDataEncode property helps simplify toggling between standard XML encoding and CDATA wrapping.


81-91: Logical ordering of removal and CDATA wrapping.

Removing invalid XML characters first and then optionally wrapping the result in CDATA looks functionally consistent.


92-95: Skipping XML-escaping when using CDATA.

Using an else if ensures XML-escaping is bypassed when CDATA is active, which aligns with the expected configuration flow.

tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs (12)

66-82: Configuration block for the Log4JXmlEventLayout.

Defining attributes like includeCallSite="true" and includeEventProperties="true" in the test config matches the intended testing scenario.


86-91: Verifying ScopeContext usage.

Clearing the context and pushing test properties/states validates that they are not included when includeScopeNested="false".


97-97: Chained exception instantiation.

Creating an inner exception ("Goodbye Exception") ensures deeper stack traces can be tested.


174-174: Validating primary and inner exception text.

Checks that both "Hello Exception" and "Goodbye Exception" appear in the final XML snippet.


184-185: AppInfo substring extraction.

Extracting the dynamic portion ensures consistent checking of the domain name and process ID.


241-241: Setting custom AppInfo.

Assigning "MyApp" ensures user-defined application info is reflected in the final log4j XML.


254-254: Double braces in escaped message.

The test verifies message layout with <, > symbols escaped and double braces for placeholders. Confirm that this meets your formatting expectations.


258-309: Test for CDATA-wrapped exception.

WriteThrowableCData = true ensures exceptions appear inside a <![CDATA[...]]> block, preventing XML-escape quirks.


314-333: Test for proper XML-escaping when CDATA is off.

Checks to ensure <, > characters in the exception are encoded in standard XML form.


335-336: Skipping obsolete test.

Marking the old renderer-based test with [Obsolete] and skipping is appropriate given the refactored XML logic.


405-453: Verifying removal of invalid XML characters.

Covers edge cases by enumerating a wide range of characters and ensuring they are sanitized.


455-477: Test for raw throwable output.

Turning off both WriteThrowableCData and ThrowableEncode ensures raw unescaped content is produced.

src/NLog.Targets.Network/Targets/ChainsawTarget.cs (1)

96-240: Refactor to delegate property access to _log4JLayout.

These pass-through properties (e.g., IncludeNdc, IncludeMdc, NdcItemSeparator) directly map to _log4JLayout fields, which is consistent with the new layout-based architecture.

src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (3)

55-147: Switching to a dedicated InnerXml layout.

InitializeLayout() populates InnerXml with attributes and elements, eliminating the old separate renderer. This design fosters clearer, more maintainable XML generation.


153-306: Parameter handling and additional flags.

Collecting custom parameters in _parameters and adding boolean flags (e.g., IncludeScopeNested, WriteThrowableCData) centralizes the log4j XML configuration.


312-312: InnerXml-based rendering.

RenderFormattedMessage now calls InnerXml.Render, removing the duplication from a separate renderer class.

@snakefoot snakefoot added this to the 6.0 milestone Apr 12, 2025
@snakefoot snakefoot added breaking change Breaking API change (different to semantic change) platform support labels Apr 12, 2025
@snakefoot snakefoot added the log4jxml-layout Log4j XML Layout label Apr 25, 2025
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 (2)
src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (2)

56-57: Prefer DateTimeKind.Utc for the epoch baseline

log4jDateBase is created with an unspecified Kind. When later subtracting evt.TimeStamp.ToUniversalTime() the framework silently ignores the mismatch, but the intent is clearly “milliseconds since the Unix epoch (UTC)”. Declaring the baseline explicitly as UTC removes any ambiguity and makes static analysis tools happier.

-private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
+private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

80-82: WriteThrowableCData changes after initialization are ignored

CDataEncode is assigned only once during InitializeLayout.
If the user toggles WriteThrowableCData at runtime (for example after loading an XML config and then adjusting programmatically), the layout will continue to use the old value because InitializeLayout() is not re-executed.

Consider either:

  1. Making WriteThrowableCData a readonly/init-only property, or
  2. Re-evaluating the flag inside a small wrapper layout, e.g.
-InnerXml.Elements.Add(new XmlElement("log4j:throwable", "${exception:format=ToString}")
-{
-    CDataEncode  = WriteThrowableCData,
-});
+InnerXml.Elements.Add(
+    new XmlElement("log4j:throwable", "${exception:format=ToString}")
+    {
+        CDataEncode = Layout.FromMethod(_ => WriteThrowableCData.ToString(), LayoutRenderOptions.ThreadAgnostic)
+    });

so the value is checked for every event.
(Any other dynamic mechanism provided by XmlElement would work as well.)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4a04bb and f4cd901.

📒 Files selected for processing (5)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (3 hunks)
  • src/NLog/Internal/XmlHelper.cs (1 hunks)
  • src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs (2 hunks)
  • src/NLog/Layouts/XML/XmlElement.cs (1 hunks)
  • tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/NLog/Layouts/XML/XmlElement.cs
  • src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs
  • tests/NLog.Targets.Network.Tests/Log4JXmlTests.cs
  • src/NLog/Internal/XmlHelper.cs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: WIP
  • GitHub Check: WIP
  • GitHub Check: WIP

@snakefoot
Copy link
Contributor

snakefoot commented Apr 26, 2025

Think the pull-request is super close to be ready for merge.

Thank you for being patient with all my comments. I hope my last suggestions are acceptable.

@ana1250
Copy link
Contributor Author

ana1250 commented Apr 26, 2025

Think the pull-request is super close to be ready for merge.

Thank you for being patient with all my comments. I hope my last suggestions are acceptable.

No worries at all! Thanks a ton for all the guidance — your feedback really helped me improve the code a lot. Appreciate you being patient too!

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

♻️ Duplicate comments (1)
src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (1)

120-129: parameter.Layout may be null – guard to prevent NullReferenceException

This exact issue was raised in an earlier review and still applies: if a user mis-configures a <parameter> element without a layout, new XmlAttribute("value", parameter.Layout) will throw.

Consider failing fast with a clear configuration message or skipping the element when the layout is missing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f4cd901 and 1050546.

📒 Files selected for processing (3)
  • src/NLog.Targets.Network/Layouts/Log4JXmlEventLayout.cs (3 hunks)
  • src/NLog/Internal/XmlHelper.cs (1 hunks)
  • src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/NLog/LayoutRenderers/Wrappers/XmlEncodeLayoutRendererWrapper.cs
  • src/NLog/Internal/XmlHelper.cs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: WIP
  • GitHub Check: WIP
  • GitHub Check: WIP

public class Log4JXmlEventLayout : Layout
{

private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Specify DateTimeKind.Utc for the epoch constant to avoid time-kind mismatch

log4jDateBase is created with DateTimeKind.Unspecified, yet it’s subtracted from evt.TimeStamp.ToUniversalTime() (kind = UTC). Mixing kinds works but triggers an implicit conversion that can bite (e.g., DateTime assertions using Kind, daylight-saving corrections in older frameworks, or analyzers warning about mismatched kinds).

-        private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
+        private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

A one-liner fix keeps the arithmetic purely UTC and future-proofs the calculation.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

Comment on lines +133 to +141
var appProperty = new XmlElement("log4j:data", null);
appProperty.Attributes.Add(new XmlAttribute("name", "log4japp"));
appProperty.Attributes.Add(new XmlAttribute("value", AppInfo));
dataProperties.Elements.Add(appProperty);

var machineProperty = new XmlElement("log4j:data", null);
machineProperty.Attributes.Add(new XmlAttribute("name", "log4jmachinename"));
machineProperty.Attributes.Add(new XmlAttribute("value", "${machinename}"));
dataProperties.Elements.Add(machineProperty);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle optional AppInfo to avoid crashes and honour defaults

AppInfo has no default value and can be left null. Adding it unconditionally causes a runtime exception inside XmlAttribute.

-            var appProperty = new XmlElement("log4j:data", null);
-            appProperty.Attributes.Add(new XmlAttribute("name", "log4japp"));
-            appProperty.Attributes.Add(new XmlAttribute("value", AppInfo));
-            dataProperties.Elements.Add(appProperty);
+            if (AppInfo is null)
+            {
+                // Fallback to a sensible default (old behaviour was `${appdomain:friendlyname}`)
+                AppInfo = "${appdomain:friendlyname}";
+            }
+
+            var appProperty = new XmlElement("log4j:data", null);
+            appProperty.Attributes.Add(new XmlAttribute("name", "log4japp"));
+            appProperty.Attributes.Add(new XmlAttribute("value", AppInfo));
+            dataProperties.Elements.Add(appProperty);

This keeps the layout resilient and preserves backward compatibility.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var appProperty = new XmlElement("log4j:data", null);
appProperty.Attributes.Add(new XmlAttribute("name", "log4japp"));
appProperty.Attributes.Add(new XmlAttribute("value", AppInfo));
dataProperties.Elements.Add(appProperty);
var machineProperty = new XmlElement("log4j:data", null);
machineProperty.Attributes.Add(new XmlAttribute("name", "log4jmachinename"));
machineProperty.Attributes.Add(new XmlAttribute("value", "${machinename}"));
dataProperties.Elements.Add(machineProperty);
// Ensure AppInfo is never null (fallback to old default if unset)
if (AppInfo is null)
{
// Fallback to a sensible default (old behaviour was `${appdomain:friendlyname}`)
AppInfo = "${appdomain:friendlyname}";
}
var appProperty = new XmlElement("log4j:data", null);
appProperty.Attributes.Add(new XmlAttribute("name", "log4japp"));
appProperty.Attributes.Add(new XmlAttribute("value", AppInfo));
dataProperties.Elements.Add(appProperty);
var machineProperty = new XmlElement("log4j:data", null);
machineProperty.Attributes.Add(new XmlAttribute("name", "log4jmachinename"));
machineProperty.Attributes.Add(new XmlAttribute("value", "${machinename}"));
dataProperties.Elements.Add(machineProperty);

@snakefoot
Copy link
Contributor

snakefoot commented Apr 26, 2025

I think the code looks great, and super happy that the NLog XmlLayout was able to lift the task. And thanks for adding the new feature CDataEncode to XmlLayout.

Do you have any more changes planned? Or should I just merge when the build-servers approves? (Then I can fiddle with getting the separator-option working again)

@ana1250
Copy link
Contributor Author

ana1250 commented Apr 26, 2025

Yup, nothing more from my side! Merge away once the build is happy.

@snakefoot
Copy link
Contributor

Closing and opening pull-request to tickle the build-servers

@snakefoot snakefoot closed this Apr 26, 2025
@snakefoot snakefoot reopened this Apr 26, 2025
@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
65.3% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

@ana1250 ana1250 changed the title [WIP] Log4JXmlEventLayout using Nlog XmlLayout Log4JXmlEventLayout using Nlog XmlLayout Apr 26, 2025
@snakefoot snakefoot merged commit 95c9e94 into NLog:dev Apr 26, 2025
5 of 6 checks passed
@welcome
Copy link

welcome bot commented Apr 26, 2025

Hooray your first pull request is merged! Thanks for the contribution! Looking for more? 👼 Please check the up-for-grabs issues - thanks!
thanks!

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

Labels

breaking change Breaking API change (different to semantic change) log4jxml-layout Log4j XML Layout platform support size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants