LogConfigTextFilePath.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Xml;
  6. namespace Wayne.Lib.Log
  7. {
  8. /// <summary>
  9. /// This class manages the path and file name to a log file,
  10. /// composing the correct name depending on datetime, id-entity properties etc.
  11. /// </summary>
  12. internal class LogConfigTextFilePath
  13. {
  14. #region Inner classes
  15. #region Param
  16. abstract class Param
  17. {
  18. public abstract string ToString(EntityCategory entityCategory);
  19. }
  20. #endregion
  21. #region ConstantTextParam
  22. class ConstantTextParam : Param
  23. {
  24. private string text;
  25. public ConstantTextParam(string text)
  26. {
  27. this.text = text;
  28. }
  29. // MLA COMMENTED OUT THIS UNUSED CODE.
  30. //public string Text
  31. //{
  32. // get { return text; }
  33. //}
  34. public override string ToString(EntityCategory entityCategory)
  35. {
  36. return text;
  37. }
  38. public override string ToString()
  39. {
  40. return text;
  41. }
  42. }
  43. class PIDParam : Param
  44. {
  45. private string text;
  46. public PIDParam()
  47. {
  48. text = Process.GetCurrentProcess().Id.ToString();
  49. }
  50. public override string ToString(EntityCategory entityCategory)
  51. {
  52. return text;
  53. }
  54. public override string ToString()
  55. {
  56. return text;
  57. }
  58. }
  59. #endregion
  60. #region EntityParamType enum
  61. enum EntityParamType
  62. {
  63. EntityType,
  64. EntitySubType
  65. }
  66. #endregion
  67. #region EntityParam
  68. class EntityParam : Param
  69. {
  70. private EntityParamType paramType;
  71. public EntityParam(EntityParamType entityParamType)
  72. {
  73. this.paramType = entityParamType;
  74. }
  75. public override string ToString(EntityCategory entityCategory)
  76. {
  77. switch (paramType)
  78. {
  79. case EntityParamType.EntityType:
  80. return entityCategory.Entity.EntityType;
  81. case EntityParamType.EntitySubType:
  82. return entityCategory.Entity.EntitySubType;
  83. default:
  84. return "";
  85. }
  86. }
  87. public override string ToString()
  88. {
  89. return "<" + paramType.ToString() + "/>";
  90. }
  91. }
  92. #endregion
  93. #region DateParam
  94. class DateParam : Param
  95. {
  96. private string dateTimeFormat;
  97. public DateParam(string dateTimeFormat)
  98. {
  99. this.dateTimeFormat = dateTimeFormat;
  100. }
  101. public override string ToString(EntityCategory entityCategory)
  102. {
  103. return DateTime.Now.ToString(dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture);
  104. }
  105. public override string ToString()
  106. {
  107. return "<Date format=" + dateTimeFormat + "/>";
  108. }
  109. }
  110. #endregion
  111. #region IdParam
  112. class IdParam : Param
  113. {
  114. private string fromEntityType;
  115. private string fromEntitySubType;
  116. public IdParam(string fromEntityType, string fromEntitySubType)
  117. {
  118. this.fromEntityType = fromEntityType;
  119. this.fromEntitySubType = fromEntitySubType;
  120. }
  121. public override string ToString(EntityCategory entityCategory)
  122. {
  123. if ((fromEntityType != null) || (fromEntitySubType != null))
  124. {
  125. IIdentifiableEntity[] ancestors = IdentifiableEntity.GetAncestorArray(entityCategory.Entity);
  126. if ((fromEntityType != null) && (fromEntitySubType != null))
  127. {
  128. foreach (IIdentifiableEntity ancestor in ancestors)
  129. {
  130. if (System.Text.RegularExpressions.Regex.IsMatch(ancestor.EntityType, fromEntityType, System.Text.RegularExpressions.RegexOptions.IgnoreCase) &&
  131. System.Text.RegularExpressions.Regex.IsMatch(ancestor.EntitySubType, fromEntitySubType, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
  132. {
  133. if (ancestor.Id != IdentifiableEntity.NoId)
  134. return ancestor.Id.ToString(System.Globalization.CultureInfo.InvariantCulture);
  135. return string.Empty;
  136. }
  137. }
  138. }
  139. else if (fromEntityType != null)
  140. {
  141. foreach (IIdentifiableEntity ancestor in ancestors)
  142. {
  143. if (System.Text.RegularExpressions.Regex.IsMatch(ancestor.EntityType, fromEntityType, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
  144. {
  145. if (ancestor.Id != IdentifiableEntity.NoId)
  146. return ancestor.Id.ToString(System.Globalization.CultureInfo.InvariantCulture);
  147. return string.Empty;
  148. }
  149. }
  150. }
  151. else
  152. {
  153. foreach (IIdentifiableEntity ancestor in ancestors)
  154. {
  155. if (System.Text.RegularExpressions.Regex.IsMatch(ancestor.EntitySubType, fromEntitySubType, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
  156. {
  157. if (ancestor.Id != IdentifiableEntity.NoId)
  158. return ancestor.Id.ToString(System.Globalization.CultureInfo.InvariantCulture);
  159. return string.Empty;
  160. }
  161. }
  162. }
  163. }
  164. else if (entityCategory.Entity.Id != IdentifiableEntity.NoId)
  165. return entityCategory.Entity.Id.ToString(System.Globalization.CultureInfo.InvariantCulture);
  166. return string.Empty;
  167. }
  168. public override string ToString()
  169. {
  170. return string.Format("<Id entityType={0}/>", fromEntityType);
  171. }
  172. }
  173. #endregion
  174. #region FileNameInvalidTimeResolution enum
  175. /// <summary>
  176. /// The resolution of the time when the log file gets a new name.
  177. /// </summary>
  178. enum FileNameInvalidTimeResolution
  179. {
  180. // The log file gets a new name every...
  181. Second,
  182. Minute,
  183. Hour,
  184. Day,
  185. Month,
  186. Year,
  187. Never
  188. }
  189. #endregion
  190. #endregion
  191. #region Fields
  192. private List<Param> paramList = new List<Param>();
  193. private FileNameInvalidTimeResolution fileNameInvalidTimeResolution; // The log file gets a new name every...
  194. private DateTime fileNameInvalidTime = DateTime.MinValue; // At this time the log file should get a new name.
  195. private Dictionary<EntityCategory, string> cachedFileNames = new Dictionary<EntityCategory, string>();
  196. private object cachedFileNamesLock = new object();
  197. private string cachedToString;
  198. private string cachedBaseName;
  199. #endregion
  200. #region Construction
  201. /// <summary>
  202. /// Construct a LogPath object from an configuration XML element.
  203. /// </summary>
  204. /// <param name="logPathElement"></param>
  205. internal LogConfigTextFilePath(XmlElement logPathElement)
  206. {
  207. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Never;
  208. for (int i = 0; i < logPathElement.ChildNodes.Count; i++)
  209. {
  210. XmlNode node = logPathElement.ChildNodes[i];
  211. if (node.NodeType == XmlNodeType.Text)
  212. {
  213. string text = node.Value.Replace("\r", "").Replace("\n", "");
  214. if (i == 0)
  215. text = text.TrimStart(' ');
  216. if (i == logPathElement.ChildNodes.Count - 1)
  217. text = text.TrimEnd(' ');
  218. paramList.Add(new ConstantTextParam(text));
  219. }
  220. else if (node.NodeType == XmlNodeType.Element)
  221. {
  222. switch (node.Name)
  223. {
  224. case "Id":
  225. XmlAttribute fromEntityTypeAttribute = node.Attributes["FromEntityType"];
  226. string fromEntityType;
  227. if (fromEntityTypeAttribute != null)
  228. fromEntityType = fromEntityTypeAttribute.Value;
  229. else
  230. fromEntityType = null;
  231. XmlAttribute fromEntitySubTypeAttribute = node.Attributes["FromEntitySubType"];
  232. string fromEntitySubType;
  233. if (fromEntitySubTypeAttribute != null)
  234. fromEntitySubType = fromEntitySubTypeAttribute.Value;
  235. else
  236. fromEntitySubType = null;
  237. paramList.Add(new IdParam(fromEntityType, fromEntitySubType));
  238. break;
  239. case "EntityType":
  240. paramList.Add(new EntityParam(EntityParamType.EntityType));
  241. break;
  242. case "EntitySubType":
  243. paramList.Add(new EntityParam(EntityParamType.EntitySubType));
  244. break;
  245. case "PID":
  246. paramList.Add(new PIDParam());
  247. break;
  248. case "Date":
  249. string dateFormat;
  250. XmlAttribute formatAttribute = node.Attributes["Format"];
  251. if (formatAttribute != null)
  252. dateFormat = formatAttribute.Value;
  253. else
  254. dateFormat = "yyyyMMdd";
  255. paramList.Add(new DateParam(dateFormat));
  256. // Find the smallest time resolution in the date format. This often the file name will be refreshed.
  257. if ((dateFormat.IndexOf("s", StringComparison.Ordinal) > -1) || (dateFormat.IndexOf("f", StringComparison.OrdinalIgnoreCase) > -1))
  258. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Second;
  259. else if ((dateFormat.IndexOf("m", StringComparison.Ordinal) > -1) && (fileNameInvalidTimeResolution > FileNameInvalidTimeResolution.Minute))
  260. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Minute;
  261. else if ((dateFormat.IndexOf("h", StringComparison.OrdinalIgnoreCase) > -1) && (fileNameInvalidTimeResolution > FileNameInvalidTimeResolution.Hour))
  262. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Hour;
  263. else if ((dateFormat.IndexOf("d", StringComparison.Ordinal) > -1) && (fileNameInvalidTimeResolution > FileNameInvalidTimeResolution.Day))
  264. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Day;
  265. else if ((dateFormat.IndexOf("M", StringComparison.Ordinal) > -1) && (fileNameInvalidTimeResolution > FileNameInvalidTimeResolution.Month))
  266. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Month;
  267. else if ((dateFormat.IndexOf("y", StringComparison.Ordinal) > -1) && (fileNameInvalidTimeResolution > FileNameInvalidTimeResolution.Year))
  268. fileNameInvalidTimeResolution = FileNameInvalidTimeResolution.Year;
  269. break;
  270. }
  271. }
  272. }
  273. }
  274. #endregion
  275. #region Methods
  276. /// <summary>
  277. /// Checks whether it's time for a new file name.
  278. /// If it is, the datetime for the next name change is calculated and all cached file names
  279. /// are deleted.
  280. /// </summary>
  281. public bool IsTimeForNewFileName()
  282. {
  283. if (DateTime.Now > fileNameInvalidTime)
  284. {
  285. lock (cachedFileNamesLock)
  286. {
  287. // All the cached file names are now invalid.
  288. cachedFileNames.Clear();
  289. }
  290. // Calculate the next time for file name change.
  291. DateTime now = DateTime.Now;
  292. switch (fileNameInvalidTimeResolution)
  293. {
  294. case FileNameInvalidTimeResolution.Second:
  295. fileNameInvalidTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Local).AddSeconds(1);
  296. break;
  297. case FileNameInvalidTimeResolution.Minute:
  298. fileNameInvalidTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Local).AddMinutes(1);
  299. break;
  300. case FileNameInvalidTimeResolution.Hour:
  301. fileNameInvalidTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, DateTimeKind.Local).AddHours(1);
  302. break;
  303. case FileNameInvalidTimeResolution.Day:
  304. fileNameInvalidTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, DateTimeKind.Local).AddDays(1);
  305. break;
  306. case FileNameInvalidTimeResolution.Month:
  307. fileNameInvalidTime = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Local).AddMonths(1);
  308. break;
  309. case FileNameInvalidTimeResolution.Year:
  310. fileNameInvalidTime = new DateTime(now.Year, 1, 1, 0, 0, 0, DateTimeKind.Local).AddYears(1);
  311. break;
  312. case FileNameInvalidTimeResolution.Never:
  313. fileNameInvalidTime = DateTime.MaxValue;
  314. break;
  315. }
  316. return true;
  317. }
  318. return false;
  319. }
  320. /// <summary>
  321. /// Equality operator
  322. /// </summary>
  323. /// <param name="obj"></param>
  324. /// <returns></returns>
  325. public override bool Equals(object obj)
  326. {
  327. return obj.ToString().Equals(this.ToString());
  328. }
  329. /// <summary>
  330. /// Hash code generator. Not correctly implemented I think....
  331. /// </summary>
  332. /// <returns></returns>
  333. public override int GetHashCode()
  334. {
  335. return this.ToString().GetHashCode();
  336. }
  337. /// <summary>
  338. /// Returns the log path using the specified identifiable entity.
  339. /// </summary>
  340. /// <returns></returns>
  341. public string ToString(EntityCategory entityCategory)
  342. {
  343. lock (cachedFileNamesLock)
  344. {
  345. string text;
  346. if (cachedFileNames.TryGetValue(entityCategory, out text))
  347. return text;
  348. StringBuilder sb = new StringBuilder();
  349. foreach (Param param in paramList)
  350. sb.Append(param.ToString(entityCategory));
  351. string fileName = sb.ToString();
  352. cachedFileNames.Add(entityCategory, fileName);
  353. return fileName;
  354. }
  355. }
  356. /// <summary>
  357. /// ToString method.
  358. /// </summary>
  359. /// <returns></returns>
  360. public override string ToString()
  361. {
  362. if (cachedToString == null)
  363. {
  364. StringBuilder sb = new StringBuilder();
  365. foreach (Param param in paramList)
  366. sb.Append(param.ToString());
  367. cachedToString = sb.ToString();
  368. }
  369. return cachedToString;
  370. }
  371. /// <summary>
  372. /// Clean the internal lists.
  373. /// </summary>
  374. /// <param name="oldestAllowedTouch"></param>
  375. internal void PerformListCleaning(DateTime oldestAllowedTouch)
  376. {
  377. lock (cachedFileNamesLock)
  378. {
  379. List<EntityCategory> entityCategoriesToRemove = new List<EntityCategory>();
  380. foreach (EntityCategory entityCategory in cachedFileNames.Keys)
  381. {
  382. if (entityCategory.LastTouched < oldestAllowedTouch)
  383. entityCategoriesToRemove.Add(entityCategory);
  384. }
  385. //Remove from the list.
  386. foreach (EntityCategory entityCategoryToRemove in entityCategoriesToRemove)
  387. {
  388. cachedFileNames.Remove(entityCategoryToRemove);
  389. }
  390. }
  391. }
  392. #endregion
  393. #region Properties
  394. /// <summary>
  395. /// Returns constant prefix base name - adds parameters until it finds a PID or Date parameter
  396. /// </summary>
  397. /// <returns></returns>
  398. public string BaseName
  399. {
  400. get
  401. {
  402. if (cachedBaseName == null)
  403. {
  404. StringBuilder sb = new StringBuilder();
  405. PIDParam pp = null;
  406. DateParam dp = null;
  407. IdParam ip = null;
  408. foreach (Param param in paramList)
  409. {
  410. pp = param as PIDParam;
  411. if (pp != null)
  412. {
  413. break;
  414. }
  415. dp = param as DateParam;
  416. if (dp != null)
  417. {
  418. break;
  419. }
  420. ip = param as IdParam;
  421. if (ip != null)
  422. {
  423. break;
  424. }
  425. if (param.ToString().IndexOf('<') >= 0) break;
  426. if (param.ToString().IndexOf('/') >= 0) break;
  427. sb.Append(param.ToString());
  428. }
  429. cachedBaseName = sb.ToString();
  430. }
  431. return cachedBaseName;
  432. }
  433. }
  434. #endregion // Properties
  435. }
  436. }