UdpAppender.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. #region Apache License
  2. //
  3. // Licensed to the Apache Software Foundation (ASF) under one or more
  4. // contributor license agreements. See the NOTICE file distributed with
  5. // this work for additional information regarding copyright ownership.
  6. // The ASF licenses this file to you under the Apache License, Version 2.0
  7. // (the "License"); you may not use this file except in compliance with
  8. // the License. You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. #endregion
  19. using System;
  20. using System.Globalization;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Text;
  24. using log4net.Layout;
  25. using log4net.Core;
  26. using log4net.Util;
  27. namespace log4net.Appender
  28. {
  29. /// <summary>
  30. /// Sends logging events as connectionless UDP datagrams to a remote host or a
  31. /// multicast group using an <see cref="UdpClient" />.
  32. /// </summary>
  33. /// <remarks>
  34. /// <para>
  35. /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order.
  36. /// </para>
  37. /// <para>
  38. /// To view the logging results, a custom application can be developed that listens for logging
  39. /// events.
  40. /// </para>
  41. /// <para>
  42. /// When decoding events send via this appender remember to use the same encoding
  43. /// to decode the events as was used to send the events. See the <see cref="Encoding"/>
  44. /// property to specify the encoding to use.
  45. /// </para>
  46. /// </remarks>
  47. /// <example>
  48. /// This example shows how to log receive logging events that are sent
  49. /// on IP address 244.0.0.1 and port 8080 to the console. The event is
  50. /// encoded in the packet as a unicode string and it is decoded as such.
  51. /// <code lang="C#">
  52. /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
  53. /// UdpClient udpClient;
  54. /// byte[] buffer;
  55. /// string loggingEvent;
  56. ///
  57. /// try
  58. /// {
  59. /// udpClient = new UdpClient(8080);
  60. ///
  61. /// while(true)
  62. /// {
  63. /// buffer = udpClient.Receive(ref remoteEndPoint);
  64. /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer);
  65. /// Console.WriteLine(loggingEvent);
  66. /// }
  67. /// }
  68. /// catch(Exception e)
  69. /// {
  70. /// Console.WriteLine(e.ToString());
  71. /// }
  72. /// </code>
  73. /// <code lang="Visual Basic">
  74. /// Dim remoteEndPoint as IPEndPoint
  75. /// Dim udpClient as UdpClient
  76. /// Dim buffer as Byte()
  77. /// Dim loggingEvent as String
  78. ///
  79. /// Try
  80. /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
  81. /// udpClient = new UdpClient(8080)
  82. ///
  83. /// While True
  84. /// buffer = udpClient.Receive(ByRef remoteEndPoint)
  85. /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer)
  86. /// Console.WriteLine(loggingEvent)
  87. /// Wend
  88. /// Catch e As Exception
  89. /// Console.WriteLine(e.ToString())
  90. /// End Try
  91. /// </code>
  92. /// <para>
  93. /// An example configuration section to log information using this appender to the
  94. /// IP 224.0.0.1 on port 8080:
  95. /// </para>
  96. /// <code lang="XML" escaped="true">
  97. /// <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
  98. /// <remoteAddress value="224.0.0.1" />
  99. /// <remotePort value="8080" />
  100. /// <layout type="log4net.Layout.PatternLayout" value="%-5level %logger [%ndc] - %message%newline" />
  101. /// </appender>
  102. /// </code>
  103. /// </example>
  104. /// <author>Gert Driesen</author>
  105. /// <author>Nicko Cadell</author>
  106. public class UdpAppender : AppenderSkeleton
  107. {
  108. #region Public Instance Constructors
  109. /// <summary>
  110. /// Initializes a new instance of the <see cref="UdpAppender" /> class.
  111. /// </summary>
  112. /// <remarks>
  113. /// The default constructor initializes all fields to their default values.
  114. /// </remarks>
  115. public UdpAppender()
  116. {
  117. }
  118. #endregion Public Instance Constructors
  119. #region Public Instance Properties
  120. /// <summary>
  121. /// Gets or sets the IP address of the remote host or multicast group to which
  122. /// the underlying <see cref="UdpClient" /> should sent the logging event.
  123. /// </summary>
  124. /// <value>
  125. /// The IP address of the remote host or multicast group to which the logging event
  126. /// will be sent.
  127. /// </value>
  128. /// <remarks>
  129. /// <para>
  130. /// Multicast addresses are identified by IP class <b>D</b> addresses (in the range 224.0.0.0 to
  131. /// 239.255.255.255). Multicast packets can pass across different networks through routers, so
  132. /// it is possible to use multicasts in an Internet scenario as long as your network provider
  133. /// supports multicasting.
  134. /// </para>
  135. /// <para>
  136. /// Hosts that want to receive particular multicast messages must register their interest by joining
  137. /// the multicast group. Multicast messages are not sent to networks where no host has joined
  138. /// the multicast group. Class <b>D</b> IP addresses are used for multicast groups, to differentiate
  139. /// them from normal host addresses, allowing nodes to easily detect if a message is of interest.
  140. /// </para>
  141. /// <para>
  142. /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below:
  143. /// </para>
  144. /// <para>
  145. /// <list type="table">
  146. /// <listheader>
  147. /// <term>IP Address</term>
  148. /// <description>Description</description>
  149. /// </listheader>
  150. /// <item>
  151. /// <term>224.0.0.1</term>
  152. /// <description>
  153. /// <para>
  154. /// Sends a message to all system on the subnet.
  155. /// </para>
  156. /// </description>
  157. /// </item>
  158. /// <item>
  159. /// <term>224.0.0.2</term>
  160. /// <description>
  161. /// <para>
  162. /// Sends a message to all routers on the subnet.
  163. /// </para>
  164. /// </description>
  165. /// </item>
  166. /// <item>
  167. /// <term>224.0.0.12</term>
  168. /// <description>
  169. /// <para>
  170. /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet.
  171. /// </para>
  172. /// </description>
  173. /// </item>
  174. /// </list>
  175. /// </para>
  176. /// <para>
  177. /// A complete list of actually reserved multicast addresses and their owners in the ranges
  178. /// defined by RFC 3171 can be found at the <A href="http://www.iana.org/assignments/multicast-addresses">IANA web site</A>.
  179. /// </para>
  180. /// <para>
  181. /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative
  182. /// addresses. These addresses can be reused with other local groups. Routers are typically
  183. /// configured with filters to prevent multicast traffic in this range from flowing outside
  184. /// of the local network.
  185. /// </para>
  186. /// </remarks>
  187. public IPAddress RemoteAddress
  188. {
  189. get { return m_remoteAddress; }
  190. set { m_remoteAddress = value; }
  191. }
  192. /// <summary>
  193. /// Gets or sets the TCP port number of the remote host or multicast group to which
  194. /// the underlying <see cref="UdpClient" /> should sent the logging event.
  195. /// </summary>
  196. /// <value>
  197. /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
  198. /// indicating the TCP port number of the remote host or multicast group to which the logging event
  199. /// will be sent.
  200. /// </value>
  201. /// <remarks>
  202. /// The underlying <see cref="UdpClient" /> will send messages to this TCP port number
  203. /// on the remote host or multicast group.
  204. /// </remarks>
  205. /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
  206. public int RemotePort
  207. {
  208. get { return m_remotePort; }
  209. set
  210. {
  211. if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)
  212. {
  213. throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
  214. "The value specified is less than " +
  215. IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
  216. " or greater than " +
  217. IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
  218. }
  219. else
  220. {
  221. m_remotePort = value;
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Gets or sets the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
  227. /// </summary>
  228. /// <value>
  229. /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" />
  230. /// indicating the TCP port number from which the underlying <see cref="UdpClient" /> will communicate.
  231. /// </value>
  232. /// <remarks>
  233. /// <para>
  234. /// The underlying <see cref="UdpClient" /> will bind to this port for sending messages.
  235. /// </para>
  236. /// <para>
  237. /// Setting the value to 0 (the default) will cause the udp client not to bind to
  238. /// a local port.
  239. /// </para>
  240. /// </remarks>
  241. /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
  242. public int LocalPort
  243. {
  244. get { return m_localPort; }
  245. set
  246. {
  247. if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort))
  248. {
  249. throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value,
  250. "The value specified is less than " +
  251. IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
  252. " or greater than " +
  253. IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
  254. }
  255. else
  256. {
  257. m_localPort = value;
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// Gets or sets <see cref="Encoding"/> used to write the packets.
  263. /// </summary>
  264. /// <value>
  265. /// The <see cref="Encoding"/> used to write the packets.
  266. /// </value>
  267. /// <remarks>
  268. /// <para>
  269. /// The <see cref="Encoding"/> used to write the packets.
  270. /// </para>
  271. /// </remarks>
  272. public Encoding Encoding
  273. {
  274. get { return m_encoding; }
  275. set { m_encoding = value; }
  276. }
  277. #endregion Public Instance Properties
  278. #region Protected Instance Properties
  279. /// <summary>
  280. /// Gets or sets the underlying <see cref="UdpClient" />.
  281. /// </summary>
  282. /// <value>
  283. /// The underlying <see cref="UdpClient" />.
  284. /// </value>
  285. /// <remarks>
  286. /// <see cref="UdpAppender" /> creates a <see cref="UdpClient" /> to send logging events
  287. /// over a network. Classes deriving from <see cref="UdpAppender" /> can use this
  288. /// property to get or set this <see cref="UdpClient" />. Use the underlying <see cref="UdpClient" />
  289. /// returned from <see cref="Client" /> if you require access beyond that which
  290. /// <see cref="UdpAppender" /> provides.
  291. /// </remarks>
  292. protected UdpClient Client
  293. {
  294. get { return this.m_client; }
  295. set { this.m_client = value; }
  296. }
  297. /// <summary>
  298. /// Gets or sets the cached remote endpoint to which the logging events should be sent.
  299. /// </summary>
  300. /// <value>
  301. /// The cached remote endpoint to which the logging events will be sent.
  302. /// </value>
  303. /// <remarks>
  304. /// The <see cref="ActivateOptions" /> method will initialize the remote endpoint
  305. /// with the values of the <see cref="RemoteAddress" /> and <see cref="RemotePort"/>
  306. /// properties.
  307. /// </remarks>
  308. protected IPEndPoint RemoteEndPoint
  309. {
  310. get { return this.m_remoteEndPoint; }
  311. set { this.m_remoteEndPoint = value; }
  312. }
  313. #endregion Protected Instance Properties
  314. #region Implementation of IOptionHandler
  315. /// <summary>
  316. /// Initialize the appender based on the options set.
  317. /// </summary>
  318. /// <remarks>
  319. /// <para>
  320. /// This is part of the <see cref="IOptionHandler"/> delayed object
  321. /// activation scheme. The <see cref="ActivateOptions"/> method must
  322. /// be called on this object after the configuration properties have
  323. /// been set. Until <see cref="ActivateOptions"/> is called this
  324. /// object is in an undefined state and must not be used.
  325. /// </para>
  326. /// <para>
  327. /// If any of the configuration properties are modified then
  328. /// <see cref="ActivateOptions"/> must be called again.
  329. /// </para>
  330. /// <para>
  331. /// The appender will be ignored if no <see cref="RemoteAddress" /> was specified or
  332. /// an invalid remote or local TCP port number was specified.
  333. /// </para>
  334. /// </remarks>
  335. /// <exception cref="ArgumentNullException">The required property <see cref="RemoteAddress" /> was not specified.</exception>
  336. /// <exception cref="ArgumentOutOfRangeException">The TCP port number assigned to <see cref="LocalPort" /> or <see cref="RemotePort" /> is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception>
  337. public override void ActivateOptions()
  338. {
  339. base.ActivateOptions();
  340. if (this.RemoteAddress == null)
  341. {
  342. throw new ArgumentNullException("The required property 'Address' was not specified.");
  343. }
  344. else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort)
  345. {
  346. throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort,
  347. "The RemotePort is less than " +
  348. IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
  349. " or greater than " +
  350. IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
  351. }
  352. else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort))
  353. {
  354. throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort,
  355. "The LocalPort is less than " +
  356. IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) +
  357. " or greater than " +
  358. IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + ".");
  359. }
  360. else
  361. {
  362. this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort);
  363. this.InitializeClientConnection();
  364. }
  365. }
  366. #endregion
  367. #region Override implementation of AppenderSkeleton
  368. /// <summary>
  369. /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
  370. /// </summary>
  371. /// <param name="loggingEvent">The event to log.</param>
  372. /// <remarks>
  373. /// <para>
  374. /// Sends the event using an UDP datagram.
  375. /// </para>
  376. /// <para>
  377. /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
  378. /// </para>
  379. /// </remarks>
  380. protected override void Append(LoggingEvent loggingEvent)
  381. {
  382. try
  383. {
  384. Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray());
  385. #if NETSTANDARD1_3
  386. Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait();
  387. #else
  388. this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint);
  389. #endif
  390. }
  391. catch (Exception ex)
  392. {
  393. ErrorHandler.Error(
  394. "Unable to send logging event to remote host " +
  395. this.RemoteAddress.ToString() +
  396. " on port " +
  397. this.RemotePort + ".",
  398. ex,
  399. ErrorCode.WriteFailure);
  400. }
  401. }
  402. /// <summary>
  403. /// This appender requires a <see cref="Layout"/> to be set.
  404. /// </summary>
  405. /// <value><c>true</c></value>
  406. /// <remarks>
  407. /// <para>
  408. /// This appender requires a <see cref="Layout"/> to be set.
  409. /// </para>
  410. /// </remarks>
  411. override protected bool RequiresLayout
  412. {
  413. get { return true; }
  414. }
  415. /// <summary>
  416. /// Closes the UDP connection and releases all resources associated with
  417. /// this <see cref="UdpAppender" /> instance.
  418. /// </summary>
  419. /// <remarks>
  420. /// <para>
  421. /// Disables the underlying <see cref="UdpClient" /> and releases all managed
  422. /// and unmanaged resources associated with the <see cref="UdpAppender" />.
  423. /// </para>
  424. /// </remarks>
  425. override protected void OnClose()
  426. {
  427. base.OnClose();
  428. if (this.Client != null)
  429. {
  430. this.Client.Close();
  431. this.Client = null;
  432. }
  433. }
  434. #endregion Override implementation of AppenderSkeleton
  435. #region Protected Instance Methods
  436. /// <summary>
  437. /// Initializes the underlying <see cref="UdpClient" /> connection.
  438. /// </summary>
  439. /// <remarks>
  440. /// <para>
  441. /// The underlying <see cref="UdpClient"/> is initialized and binds to the
  442. /// port number from which you intend to communicate.
  443. /// </para>
  444. /// <para>
  445. /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>.
  446. /// </para>
  447. /// </remarks>
  448. protected virtual void InitializeClientConnection()
  449. {
  450. try
  451. {
  452. if (this.LocalPort == 0)
  453. {
  454. #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
  455. this.Client = new UdpClient();
  456. #else
  457. this.Client = new UdpClient(RemoteAddress.AddressFamily);
  458. #endif
  459. }
  460. else
  461. {
  462. #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0
  463. this.Client = new UdpClient(this.LocalPort);
  464. #else
  465. this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily);
  466. #endif
  467. }
  468. }
  469. catch (Exception ex)
  470. {
  471. ErrorHandler.Error(
  472. "Could not initialize the UdpClient connection on port " +
  473. this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".",
  474. ex,
  475. ErrorCode.GenericFailure);
  476. this.Client = null;
  477. }
  478. }
  479. #endregion Protected Instance Methods
  480. #region Private Instance Fields
  481. /// <summary>
  482. /// The IP address of the remote host or multicast group to which
  483. /// the logging event will be sent.
  484. /// </summary>
  485. private IPAddress m_remoteAddress;
  486. /// <summary>
  487. /// The TCP port number of the remote host or multicast group to
  488. /// which the logging event will be sent.
  489. /// </summary>
  490. private int m_remotePort;
  491. /// <summary>
  492. /// The cached remote endpoint to which the logging events will be sent.
  493. /// </summary>
  494. private IPEndPoint m_remoteEndPoint;
  495. /// <summary>
  496. /// The TCP port number from which the <see cref="UdpClient" /> will communicate.
  497. /// </summary>
  498. private int m_localPort;
  499. /// <summary>
  500. /// The <see cref="UdpClient" /> instance that will be used for sending the
  501. /// logging events.
  502. /// </summary>
  503. private UdpClient m_client;
  504. /// <summary>
  505. /// The encoding to use for the packet.
  506. /// </summary>
  507. #if NETSTANDARD1_3
  508. private Encoding m_encoding = Encoding.Unicode;
  509. #else
  510. private Encoding m_encoding = Encoding.Default;
  511. #endif
  512. #endregion Private Instance Fields
  513. }
  514. }