The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Logger.cs 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Mail;
  7. using System.Text;
  8. using Teknik.Configuration;
  9. using Teknik.Utilities;
  10. namespace Teknik.Logging
  11. {
  12. public class Logger : ILogger
  13. {
  14. private static readonly object Locker = new object();
  15. private readonly string _name;
  16. private readonly Config _config;
  17. public Logger(string name, Config config)
  18. {
  19. _name = name;
  20. _config = config;
  21. }
  22. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
  23. {
  24. if (!IsEnabled(logLevel))
  25. return;
  26. // write an entry to the logs
  27. LogMessage log = new LogMessage();
  28. log.Level = logLevel;
  29. log.Message = formatter(state, exception);
  30. log.Exception = exception;
  31. WriteLogMessage(log);
  32. }
  33. public bool IsEnabled(LogLevel logLevel)
  34. {
  35. if (_config.LoggingConfig.Enabled)
  36. {
  37. // Do we want to write a log for this level? (Default to Error)
  38. LogLevel minLogLevel = LogLevel.Error;
  39. Enum.TryParse(_config.LoggingConfig.LogLevel, out minLogLevel);
  40. if (logLevel >= minLogLevel)
  41. return true;
  42. }
  43. return false;
  44. }
  45. public IDisposable BeginScope<TState>(TState state)
  46. {
  47. return null;
  48. }
  49. private void WriteLogMessage(LogMessage log)
  50. {
  51. try
  52. {
  53. // Lock the file processing so only 1 thread is working on the log file at a time
  54. lock (Locker)
  55. {
  56. if (!Directory.Exists(_config.LoggingConfig.OutputDirectory))
  57. {
  58. Directory.CreateDirectory(_config.LoggingConfig.OutputDirectory);
  59. }
  60. // Get current log file
  61. string fileName = Constants.LOG_FILE_NAME_PREFIX + Constants.LOG_FILE_EXT;
  62. string logFile = Path.Combine(_config.LoggingConfig.OutputDirectory, fileName);
  63. if (File.Exists(logFile))
  64. {
  65. // File already exists, so lets see if we need to rotate it
  66. if (_config.LoggingConfig.RotateLogs)
  67. {
  68. FileInfo info = new FileInfo(logFile);
  69. if (_config.LoggingConfig.MaxSize < info.Length && _config.LoggingConfig.MaxSize > 0)
  70. {
  71. // File is too large, so let's create a new name for it based on todays date
  72. string newFileName = Constants.LOG_FILE_NAME_PREFIX + "_" + DateTime.Now.ToString("yyyyMMdd") + Constants.LOG_FILE_EXT;
  73. newFileName = FileHelper.MakeUniqueFilename(newFileName, _config.LoggingConfig.OutputDirectory);
  74. string newLog = Path.Combine(_config.LoggingConfig.OutputDirectory, newFileName);
  75. // Move the current file to the new file
  76. File.Move(logFile, newLog);
  77. }
  78. // Make sure we have less than the max number of logs
  79. List<string> totalFiles = Directory.GetFiles(_config.LoggingConfig.OutputDirectory, string.Format("{0}*{1}", Constants.LOG_FILE_NAME_PREFIX, Constants.LOG_FILE_EXT), SearchOption.TopDirectoryOnly).ToList();
  80. if (totalFiles.Count + 1 > _config.LoggingConfig.MaxCount && _config.LoggingConfig.MaxCount > 0)
  81. {
  82. // We will have too many logs, so let's remove the last one
  83. totalFiles.Sort();
  84. string fileToRemove = totalFiles[totalFiles.Count - 1];
  85. File.Delete(fileToRemove);
  86. }
  87. }
  88. }
  89. // We have rotated if needed, so let's write the entry
  90. File.AppendAllText(logFile, log.ToString() + Environment.NewLine);
  91. }
  92. }
  93. catch (Exception) { } // If we throw when writing the log, still try to send the email if needed
  94. try
  95. {
  96. // Send Email Message if enabled
  97. if (_config.LoggingConfig.SendEmail)
  98. {
  99. // Do we want to send an email for this level? (Default to error)
  100. LogLevel minEmailLevel = LogLevel.Error;
  101. Enum.TryParse(_config.LoggingConfig.EmailLevel, out minEmailLevel);
  102. if (log.Level >= minEmailLevel)
  103. {
  104. string subject = string.Format("{0} Log Message", log.Level);
  105. string message = "Message: " + log.Message;
  106. if (log.Exception != null)
  107. {
  108. message += Environment.NewLine + Environment.NewLine + "Exception: " + log.Exception.GetFullMessage(true, true);
  109. }
  110. SendErrorEmail(subject, message);
  111. }
  112. }
  113. }
  114. catch (Exception)
  115. {
  116. // Can't do anything about it. :/
  117. }
  118. }
  119. private void SendErrorEmail(string subject, string message)
  120. {
  121. try
  122. {
  123. // Let's also email the message to support
  124. SmtpClient client = new SmtpClient();
  125. client.Host = _config.LoggingConfig.SenderAccount.Host;
  126. client.Port = _config.LoggingConfig.SenderAccount.Port;
  127. client.EnableSsl = _config.LoggingConfig.SenderAccount.SSL;
  128. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  129. client.UseDefaultCredentials = true;
  130. client.Credentials = new System.Net.NetworkCredential(_config.LoggingConfig.SenderAccount.Username, _config.LoggingConfig.SenderAccount.Password);
  131. client.Timeout = 5000;
  132. MailMessage mail = new MailMessage(_config.LoggingConfig.SenderAccount.EmailAddress, _config.LoggingConfig.RecipientEmailAddress);
  133. mail.Subject = subject;
  134. mail.Body = message;
  135. mail.BodyEncoding = UTF8Encoding.UTF8;
  136. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  137. client.Send(mail);
  138. }
  139. catch (Exception) { /* don't handle something in the handler */
  140. }
  141. }
  142. }
  143. }