Skip to content

#255 Asynchronous Sending for RemoteSyslogAppender in log4net #258

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/log4net.Tests/Appender/Internal/UdpMock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using log4net.Appender.Internal;

namespace log4net.Tests.Appender.Internal;

/// <summary>
/// Mock implementation of <see cref="IUdpConnection"/> for testing purposes.
/// </summary>
internal sealed class UdpMock : IUdpConnection
{
/// <summary>
/// Passed to <see cref="SendAsync(byte[], int)"/>
/// </summary>
public List<(byte[] Datagram, int Bytes)> Sent { get; } = [];

/// <summary>
/// Was <see cref="Dispose"/> called
/// </summary>
internal bool WasDisposed { get; private set; }

/// <summary>
/// Parameters passed to <see cref="Connect(int, IPAddress, int)"/>
/// </summary>
internal (int LocalPort, IPAddress Host, int RemotePort)? ConnectedTo { get; private set; }

/// <inheritdoc/>
public void Connect(int localPort, IPAddress host, int remotePort)
=> ConnectedTo = (localPort, host, remotePort);

/// <inheritdoc/>
public void Dispose() => WasDisposed = true;

/// <inheritdoc/>
public Task<int> SendAsync(byte[] datagram, int bytes)
{
Sent.Add((datagram, bytes));
return Task.FromResult(bytes);
}
}
75 changes: 75 additions & 0 deletions src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System.Text;
using log4net.Appender;
using log4net.Appender.Internal;
using log4net.Core;
using log4net.Layout;
using log4net.Tests.Appender.Internal;
using NUnit.Framework;

namespace log4net.Tests.Appender;

/// <summary>
/// Tests for <see cref="RemoteSyslogAppender"/>
/// </summary>
[TestFixture]
public sealed class RemoteSyslogAppenderTest
{
private sealed class RemoteAppender : RemoteSyslogAppender
{
/// <summary>
/// Mock
/// </summary>
internal UdpMock Mock { get; } = new();

/// <inheritdoc/>
protected override IUdpConnection CreateUdpConnection() => Mock;
}

/// <summary>
/// Simple Test for the <see cref="RemoteSyslogAppenderTest"/>
/// </summary>
/// <remarks>
/// https://github.com/apache/logging-log4net/issues/255
/// </remarks>
[Test]
public void RemoteSyslogTest()
{
System.Net.IPAddress ipAddress = new([127, 0, 0, 1]);
RemoteAppender appender = new() { RemoteAddress = ipAddress, Layout = new PatternLayout("%-5level - %message%newline") };
appender.ActivateOptions();
LoggingEvent loggingEvent = new(new()
{
Level = Level.Info,
Message = "Test message",
LoggerName = "TestLogger",
Domain = "TestDomain",
});
appender.DoAppend(loggingEvent);
appender.Close();
Assert.That(appender.Mock.ConnectedTo, Is.EqualTo((0, ipAddress, 514)));
Assert.That(appender.Mock.Sent, Has.Count.EqualTo(1));
Assert.That(appender.Mock.WasDisposed, Is.True);
Assert.That(appender.Mock.Sent, Has.Count.EqualTo(1));
const string expectedData = @"<14>TestDomain: INFO - Test message";
Assert.That(Encoding.ASCII.GetString(appender.Mock.Sent[0].Datagram), Is.EqualTo(expectedData));
}
}
4 changes: 2 additions & 2 deletions src/log4net.Tests/Appender/TelnetAppenderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand Down Expand Up @@ -37,7 +37,7 @@ namespace log4net.Tests.Appender;
public sealed class TelnetAppenderTest
{
/// <summary>
/// Simple Test für the <see cref="TelnetAppender"/>
/// Simple Test for the <see cref="TelnetAppender"/>
/// </summary>
/// <remarks>
/// https://github.com/apache/logging-log4net/issues/194
Expand Down
4 changes: 2 additions & 2 deletions src/log4net/Appender/AppenderSkeleton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ public void DoAppend(LoggingEvent[] loggingEvents)
{
_recursiveGuard = true;

var filteredEvents = new List<LoggingEvent>(loggingEvents.Length);
List<LoggingEvent> filteredEvents = new(loggingEvents.Length);

foreach (LoggingEvent loggingEvent in loggingEvents)
{
Expand Down Expand Up @@ -628,7 +628,7 @@ protected string RenderLoggingEvent(LoggingEvent loggingEvent)
lock (LockObj)
{
// Create the render writer on first use
_renderWriter ??= new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture);
_renderWriter ??= new(System.Globalization.CultureInfo.InvariantCulture);

// Reset the writer so we can reuse it
_renderWriter.Reset(RenderBufferMaxCapacity, RenderBufferSize);
Expand Down
51 changes: 51 additions & 0 deletions src/log4net/Appender/Internal/IUdpConnection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System;
using System.ComponentModel;
using System.Net;
using System.Threading.Tasks;

namespace log4net.Appender.Internal;

/// <summary>
/// Interface for UDP connection management.
/// Only public for unit testing purposes.
/// Do not use outside of log4net.
/// Signatures may change without notice.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public interface IUdpConnection : IDisposable
{
/// <summary>
/// Establishes a default remote host using the specified host name and port number.
/// </summary>
/// <param name="localPort">The local port number</param>
/// <param name="host">The remote host to which you intend send data.</param>
/// <param name="remotePort">The port number on the remote host to which you intend to send data.</param>
void Connect(int localPort, IPAddress host, int remotePort);

/// <summary>
/// Sends a UDP datagram asynchronously to a remote host.
/// </summary>
/// <param name="datagram">An array of type System.Byte that specifies the UDP datagram that you intend to send represented as an array of bytes.</param>
/// <param name="bytes">The number of bytes in the datagram.</param>
/// <returns>Task for Completion</returns>
Task<int> SendAsync(byte[] datagram, int bytes);
}
58 changes: 58 additions & 0 deletions src/log4net/Appender/Internal/UdpConnection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using log4net.Util;

namespace log4net.Appender.Internal;

/// <summary>
/// Wrapper for <see cref="UdpClient"/> to manage UDP connections.
/// </summary>
internal sealed class UdpConnection : IUdpConnection
{
private UdpClient? _client;

private UdpClient Client
=> _client.EnsureNotNull(errorMessage: "Client is not initialized. Call Connect first.");

/// <inheritdoc/>
public void Connect(int localPort, IPAddress remoteAddress, int remotePort)
{
_client = CreateClient(localPort, remoteAddress);
Client.Connect(remoteAddress, remotePort);
}

/// <inheritdoc/>
public Task<int> SendAsync(byte[] datagram, int bytes) => Client.SendAsync(datagram, bytes);

/// <inheritdoc/>
public void Dispose() => _client?.Dispose();

/// <summary>
/// Creates a new <see cref="UdpClient"/> instance configured with the specified local port and remote address.
/// </summary>
/// <returns>A <see cref="UdpClient"/> instance configured with the specified parameters.</returns>
internal static UdpClient CreateClient(int localPort, System.Net.IPAddress remoteAddress)
=> localPort == 0
? new (remoteAddress.AddressFamily)
: new (localPort, remoteAddress.AddressFamily);
}
Loading