SmtpPickupDirAppender.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.Text;
  21. using System.IO;
  22. using log4net.Layout;
  23. using log4net.Core;
  24. using log4net.Util;
  25. namespace log4net.Appender
  26. {
  27. /// <summary>
  28. /// Send an email when a specific logging event occurs, typically on errors
  29. /// or fatal errors. Rather than sending via smtp it writes a file into the
  30. /// directory specified by <see cref="PickupDir"/>. This allows services such
  31. /// as the IIS SMTP agent to manage sending the messages.
  32. /// </summary>
  33. /// <remarks>
  34. /// <para>
  35. /// The configuration for this appender is identical to that of the <c>SMTPAppender</c>,
  36. /// except that instead of specifying the <c>SMTPAppender.SMTPHost</c> you specify
  37. /// <see cref="PickupDir"/>.
  38. /// </para>
  39. /// <para>
  40. /// The number of logging events delivered in this e-mail depend on
  41. /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
  42. /// <see cref="SmtpPickupDirAppender"/> keeps only the last
  43. /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
  44. /// cyclic buffer. This keeps memory requirements at a reasonable level while
  45. /// still delivering useful application context.
  46. /// </para>
  47. /// </remarks>
  48. /// <author>Niall Daley</author>
  49. /// <author>Nicko Cadell</author>
  50. public class SmtpPickupDirAppender : BufferingAppenderSkeleton
  51. {
  52. #region Public Instance Constructors
  53. /// <summary>
  54. /// Default constructor
  55. /// </summary>
  56. /// <remarks>
  57. /// <para>
  58. /// Default constructor
  59. /// </para>
  60. /// </remarks>
  61. public SmtpPickupDirAppender()
  62. {
  63. m_fileExtension = string.Empty; // Default to empty string, not null
  64. }
  65. #endregion Public Instance Constructors
  66. #region Public Instance Properties
  67. /// <summary>
  68. /// Gets or sets a semicolon-delimited list of recipient e-mail addresses.
  69. /// </summary>
  70. /// <value>
  71. /// A semicolon-delimited list of e-mail addresses.
  72. /// </value>
  73. /// <remarks>
  74. /// <para>
  75. /// A semicolon-delimited list of e-mail addresses.
  76. /// </para>
  77. /// </remarks>
  78. public string To
  79. {
  80. get { return m_to; }
  81. set { m_to = value; }
  82. }
  83. /// <summary>
  84. /// Gets or sets the e-mail address of the sender.
  85. /// </summary>
  86. /// <value>
  87. /// The e-mail address of the sender.
  88. /// </value>
  89. /// <remarks>
  90. /// <para>
  91. /// The e-mail address of the sender.
  92. /// </para>
  93. /// </remarks>
  94. public string From
  95. {
  96. get { return m_from; }
  97. set { m_from = value; }
  98. }
  99. /// <summary>
  100. /// Gets or sets the subject line of the e-mail message.
  101. /// </summary>
  102. /// <value>
  103. /// The subject line of the e-mail message.
  104. /// </value>
  105. /// <remarks>
  106. /// <para>
  107. /// The subject line of the e-mail message.
  108. /// </para>
  109. /// </remarks>
  110. public string Subject
  111. {
  112. get { return m_subject; }
  113. set { m_subject = value; }
  114. }
  115. /// <summary>
  116. /// Gets or sets the path to write the messages to.
  117. /// </summary>
  118. /// <remarks>
  119. /// <para>
  120. /// Gets or sets the path to write the messages to. This should be the same
  121. /// as that used by the agent sending the messages.
  122. /// </para>
  123. /// </remarks>
  124. public string PickupDir
  125. {
  126. get { return m_pickupDir; }
  127. set { m_pickupDir = value; }
  128. }
  129. /// <summary>
  130. /// Gets or sets the file extension for the generated files
  131. /// </summary>
  132. /// <value>
  133. /// The file extension for the generated files
  134. /// </value>
  135. /// <remarks>
  136. /// <para>
  137. /// The file extension for the generated files
  138. /// </para>
  139. /// </remarks>
  140. public string FileExtension
  141. {
  142. get { return m_fileExtension; }
  143. set
  144. {
  145. m_fileExtension = value;
  146. if (m_fileExtension == null)
  147. {
  148. m_fileExtension = string.Empty;
  149. }
  150. // Make sure any non empty extension starts with a dot
  151. #if NET_2_0 || MONO_2_0
  152. if (!string.IsNullOrEmpty(m_fileExtension) && !m_fileExtension.StartsWith("."))
  153. #else
  154. if (m_fileExtension != null && m_fileExtension.Length > 0 && !m_fileExtension.StartsWith("."))
  155. #endif
  156. {
  157. m_fileExtension = "." + m_fileExtension;
  158. }
  159. }
  160. }
  161. /// <summary>
  162. /// Gets or sets the <see cref="SecurityContext"/> used to write to the pickup directory.
  163. /// </summary>
  164. /// <value>
  165. /// The <see cref="SecurityContext"/> used to write to the pickup directory.
  166. /// </value>
  167. /// <remarks>
  168. /// <para>
  169. /// Unless a <see cref="SecurityContext"/> specified here for this appender
  170. /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
  171. /// security context to use. The default behavior is to use the security context
  172. /// of the current thread.
  173. /// </para>
  174. /// </remarks>
  175. public SecurityContext SecurityContext
  176. {
  177. get { return m_securityContext; }
  178. set { m_securityContext = value; }
  179. }
  180. #endregion Public Instance Properties
  181. #region Override implementation of BufferingAppenderSkeleton
  182. /// <summary>
  183. /// Sends the contents of the cyclic buffer as an e-mail message.
  184. /// </summary>
  185. /// <param name="events">The logging events to send.</param>
  186. /// <remarks>
  187. /// <para>
  188. /// Sends the contents of the cyclic buffer as an e-mail message.
  189. /// </para>
  190. /// </remarks>
  191. override protected void SendBuffer(LoggingEvent[] events)
  192. {
  193. // Note: this code already owns the monitor for this
  194. // appender. This frees us from needing to synchronize again.
  195. try
  196. {
  197. string filePath = null;
  198. StreamWriter writer = null;
  199. // Impersonate to open the file
  200. using(SecurityContext.Impersonate(this))
  201. {
  202. filePath = Path.Combine(m_pickupDir, SystemInfo.NewGuid().ToString("N") + m_fileExtension);
  203. writer = File.CreateText(filePath);
  204. }
  205. if (writer == null)
  206. {
  207. ErrorHandler.Error("Failed to create output file for writing ["+filePath+"]", null, ErrorCode.FileOpenFailure);
  208. }
  209. else
  210. {
  211. using(writer)
  212. {
  213. writer.WriteLine("To: " + m_to);
  214. writer.WriteLine("From: " + m_from);
  215. writer.WriteLine("Subject: " + m_subject);
  216. writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r"));
  217. writer.WriteLine("");
  218. string t = Layout.Header;
  219. if (t != null)
  220. {
  221. writer.Write(t);
  222. }
  223. for(int i = 0; i < events.Length; i++)
  224. {
  225. // Render the event and append the text to the buffer
  226. RenderLoggingEvent(writer, events[i]);
  227. }
  228. t = Layout.Footer;
  229. if (t != null)
  230. {
  231. writer.Write(t);
  232. }
  233. writer.WriteLine("");
  234. writer.WriteLine(".");
  235. }
  236. }
  237. }
  238. catch(Exception e)
  239. {
  240. ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
  241. }
  242. }
  243. #endregion Override implementation of BufferingAppenderSkeleton
  244. #region Override implementation of AppenderSkeleton
  245. /// <summary>
  246. /// Activate the options on this appender.
  247. /// </summary>
  248. /// <remarks>
  249. /// <para>
  250. /// This is part of the <see cref="IOptionHandler"/> delayed object
  251. /// activation scheme. The <see cref="ActivateOptions"/> method must
  252. /// be called on this object after the configuration properties have
  253. /// been set. Until <see cref="ActivateOptions"/> is called this
  254. /// object is in an undefined state and must not be used.
  255. /// </para>
  256. /// <para>
  257. /// If any of the configuration properties are modified then
  258. /// <see cref="ActivateOptions"/> must be called again.
  259. /// </para>
  260. /// </remarks>
  261. override public void ActivateOptions()
  262. {
  263. base.ActivateOptions();
  264. if (m_securityContext == null)
  265. {
  266. m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
  267. }
  268. using(SecurityContext.Impersonate(this))
  269. {
  270. m_pickupDir = ConvertToFullPath(m_pickupDir.Trim());
  271. }
  272. }
  273. /// <summary>
  274. /// This appender requires a <see cref="Layout"/> to be set.
  275. /// </summary>
  276. /// <value><c>true</c></value>
  277. /// <remarks>
  278. /// <para>
  279. /// This appender requires a <see cref="Layout"/> to be set.
  280. /// </para>
  281. /// </remarks>
  282. override protected bool RequiresLayout
  283. {
  284. get { return true; }
  285. }
  286. #endregion Override implementation of AppenderSkeleton
  287. #region Protected Static Methods
  288. /// <summary>
  289. /// Convert a path into a fully qualified path.
  290. /// </summary>
  291. /// <param name="path">The path to convert.</param>
  292. /// <returns>The fully qualified path.</returns>
  293. /// <remarks>
  294. /// <para>
  295. /// Converts the path specified to a fully
  296. /// qualified path. If the path is relative it is
  297. /// taken as relative from the application base
  298. /// directory.
  299. /// </para>
  300. /// </remarks>
  301. protected static string ConvertToFullPath(string path)
  302. {
  303. return SystemInfo.ConvertToFullPath(path);
  304. }
  305. #endregion Protected Static Methods
  306. #region Private Instance Fields
  307. private string m_to;
  308. private string m_from;
  309. private string m_subject;
  310. private string m_pickupDir;
  311. private string m_fileExtension;
  312. /// <summary>
  313. /// The security context to use for privileged calls
  314. /// </summary>
  315. private SecurityContext m_securityContext;
  316. #endregion Private Instance Fields
  317. }
  318. }