форкнуто от Teknikode/Teknik
1
0
Форкнуть 0
Просмотр исходного кода

Created logging utility to handle writing log messages and sending emails.

master
Teknikode 5 лет назад
Родитель
Сommit
fc08678d7d
  1. 2
      Teknik/Areas/Upload/Uploader.cs
  2. 43
      Utilities/Logging/LogMessage.cs
  3. 59
      Utilities/Logging/Logger.cs
  4. 134
      Utilities/Logging/Logging.cs
  5. 2
      Utilities/Logging/Logging.csproj
  6. 2
      Utilities/Utilities/Constants.cs
  7. 35
      Utilities/Utilities/FileHelper.cs

2
Teknik/Areas/Upload/Uploader.cs

@ -38,7 +38,7 @@ namespace Teknik.Areas.Upload @@ -38,7 +38,7 @@ namespace Teknik.Areas.Upload
}
// Generate a unique file name that does not currently exist
string filePath = FileHelper.GenerateUniqueFileName(config.UploadConfig.UploadDirectory, config.UploadConfig.FileExtension, 10);
string filePath = FileHelper.GenerateRandomFileName(config.UploadConfig.UploadDirectory, config.UploadConfig.FileExtension, 10);
string fileName = Path.GetFileName(filePath);
// once we have the filename, lets save the file

43
Utilities/Logging/LogMessage.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teknik.Utilities;
namespace Teknik.Logging
{
public class LogMessage
{
public LogLevel Level { get; set; }
public DateTime EntryDate { get; set; }
public string Message { get; set; }
public Exception Exception { get; set; }
public LogMessage()
{
SetDefaults();
}
public void SetDefaults()
{
Level = LogLevel.Info;
EntryDate = DateTime.Now;
Message = string.Empty;
Exception = null;
}
public override string ToString()
{
// Create the full message we want to log
string fullMessage = Message;
if (Exception != null)
{
fullMessage += " | Exception: " + Exception.GetFullMessage(true, true);
}
// We have rotated if needed, so let's write the entry
return string.Format("{0} | {1} | {2}", Level, EntryDate.ToString("yyyy-MM-dd HH:mm:ss.fff"), fullMessage);
}
}
}

59
Utilities/Logging/Logger.cs

@ -1,59 +0,0 @@ @@ -1,59 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Teknik.Configuration;
namespace Teknik.Logging
{
public class Logger
{
private Config m_Config;
public Logger(Config config)
{
m_Config = config;
}
public void WriteEntry(Exception ex)
{
// write an entry to the logs
}
public void WriteEntry(string message, LogLevel level)
{
if (m_Config.LoggingConfig.Enabled)
{
}
}
private void SendErrorEmail(string subject, string message)
{
try
{
// Let's also email the message to support
SmtpClient client = new SmtpClient();
client.Host = m_Config.LoggingConfig.SenderAccount.Host;
client.Port = m_Config.LoggingConfig.SenderAccount.Port;
client.EnableSsl = m_Config.LoggingConfig.SenderAccount.SSL;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Credentials = new System.Net.NetworkCredential(m_Config.LoggingConfig.SenderAccount.Username, m_Config.LoggingConfig.SenderAccount.Password);
client.Timeout = 5000;
MailMessage mail = new MailMessage(m_Config.LoggingConfig.SenderAccount.EmailAddress, m_Config.LoggingConfig.RecipientEmailAddress);
mail.Subject = subject;
mail.Body = message;
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
client.Send(mail);
}
catch (Exception) { /* don't handle something in the handler */ }
}
}
}

134
Utilities/Logging/Logging.cs

@ -1,26 +1,150 @@ @@ -1,26 +1,150 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Teknik.Configuration;
using Teknik.Utilities;
namespace Teknik.Logging
{
public static class Logging
{
public static Logger Logger
private static Config m_Config
{
get
{
return Create();
return Config.Load();
}
}
public static Logger Create()
public static void WriteEntry(string message)
{
Config curConfig = Config.Load();
return new Logger(curConfig);
WriteEntry(LogLevel.Info, message, null);
}
public static void WriteEntry(LogLevel level, string message)
{
WriteEntry(level, message, null);
}
public static void WriteEntry(Exception ex)
{
WriteEntry(LogLevel.Error, ex.Message, ex);
}
public static void WriteEntry(string message, Exception ex)
{
WriteEntry(LogLevel.Error, message, ex);
}
public static void WriteEntry(LogLevel level, string message, Exception exception)
{
// write an entry to the logs
LogMessage log = new LogMessage();
log.Level = level;
log.Message = message;
log.Exception = exception;
WriteEntry(log);
}
public static void WriteEntry(LogMessage log)
{
if (m_Config.LoggingConfig.Enabled)
{
// Do we want to write a log for this level? (Default to Error)
LogLevel minLogLevel = LogLevel.Error;
Enum.TryParse(m_Config.LoggingConfig.EmailLevel, out minLogLevel);
if (log.Level >= minLogLevel)
{
if (!Directory.Exists(m_Config.LoggingConfig.OutputDirectory))
{
Directory.CreateDirectory(m_Config.LoggingConfig.OutputDirectory);
}
// Get current log file
string fileName = Constants.LOG_FILE_NAME_PREFIX + Constants.LOG_FILE_EXT;
string logFile = Path.Combine(m_Config.LoggingConfig.OutputDirectory, fileName);
if (File.Exists(logFile))
{
// File already exists, so lets see if we need to rotate it
if (m_Config.LoggingConfig.RotateLogs)
{
FileInfo info = new FileInfo(logFile);
if (m_Config.LoggingConfig.MaxSize < info.Length && m_Config.LoggingConfig.MaxSize > 0)
{
// File is too large, so let's create a new name for it based on todays date
string newFileName = Constants.LOG_FILE_NAME_PREFIX + "_" + DateTime.Now.ToString("yyyyMMdd") + Constants.LOG_FILE_EXT;
newFileName = FileHelper.MakeUniqueFilename(newFileName, m_Config.LoggingConfig.OutputDirectory);
string newLog = Path.Combine(m_Config.LoggingConfig.OutputDirectory, newFileName);
// Move the current file to the new file
File.Move(logFile, newLog);
}
// Make sure we have less than the max number of logs
List<string> totalFiles = Directory.GetFiles(m_Config.LoggingConfig.OutputDirectory, string.Format("{0}*{1}", Constants.LOG_FILE_NAME_PREFIX, Constants.LOG_FILE_EXT), SearchOption.TopDirectoryOnly).ToList();
if (totalFiles.Count + 1 > m_Config.LoggingConfig.MaxCount && m_Config.LoggingConfig.MaxCount > 0)
{
// We will have too many logs, so let's remove the last one
totalFiles.Sort();
string fileToRemove = totalFiles[totalFiles.Count - 1];
File.Delete(fileToRemove);
}
}
}
// We have rotated if needed, so let's write the entry
File.AppendAllText(logFile, log.ToString());
}
// Send Email Message if enabled
if (m_Config.LoggingConfig.SendEmail)
{
// Do we want to send an email for this level? (Default to error)
LogLevel minEmailLevel = LogLevel.Error;
Enum.TryParse(m_Config.LoggingConfig.EmailLevel, out minEmailLevel);
if (log.Level >= minEmailLevel)
{
string subject = string.Format("{0} Log Message");
string message = "Message: " + log.Message;
if (log.Exception != null)
{
message += Environment.NewLine + Environment.NewLine + "Exception: " + log.Exception.GetFullMessage(true, true);
}
SendErrorEmail(subject, message);
}
}
}
}
private static void SendErrorEmail(string subject, string message)
{
try
{
// Let's also email the message to support
SmtpClient client = new SmtpClient();
client.Host = m_Config.LoggingConfig.SenderAccount.Host;
client.Port = m_Config.LoggingConfig.SenderAccount.Port;
client.EnableSsl = m_Config.LoggingConfig.SenderAccount.SSL;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Credentials = new System.Net.NetworkCredential(m_Config.LoggingConfig.SenderAccount.Username, m_Config.LoggingConfig.SenderAccount.Password);
client.Timeout = 5000;
MailMessage mail = new MailMessage(m_Config.LoggingConfig.SenderAccount.EmailAddress, m_Config.LoggingConfig.RecipientEmailAddress);
mail.Subject = subject;
mail.Body = message;
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
client.Send(mail);
}
catch (Exception) { /* don't handle something in the handler */ }
}
}
}

2
Utilities/Logging/Logging.csproj

@ -43,9 +43,9 @@ @@ -43,9 +43,9 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Logger.cs" />
<Compile Include="Logging.cs" />
<Compile Include="LogLevel.cs" />
<Compile Include="LogMessage.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>

2
Utilities/Utilities/Constants.cs

@ -8,5 +8,7 @@ @@ -8,5 +8,7 @@
public const string LOGO_PATH = "~/Images/logo-black.svg";
public const string FAVICON_PATH = "~/Images/favicon.ico";
public const string ROBOTS_PATH = "~/App_Data/robots.txt";
public const string LOG_FILE_NAME_PREFIX = "Teknik";
public const string LOG_FILE_EXT = ".log";
}
}

35
Utilities/Utilities/FileHelper.cs

@ -10,7 +10,7 @@ namespace Teknik.Utilities @@ -10,7 +10,7 @@ namespace Teknik.Utilities
{
public static class FileHelper
{
public static string GenerateUniqueFileName(string path, string extension, int length)
public static string GenerateRandomFileName(string path, string extension, int length)
{
if (Directory.Exists(path))
{
@ -38,6 +38,39 @@ namespace Teknik.Utilities @@ -38,6 +38,39 @@ namespace Teknik.Utilities
return string.Empty;
}
/// <summary>
/// Append a number to the end of a file name to make it unique, incrementing the number if needed
/// </summary>
/// <param name="file">the name of the file, including extension</param>
/// <param name="destinationFolder">the destination folder in which to check for uniqueness</param>
/// <returns>the file name, without folder, with extension, with a unique index as the suffix, if necessary</returns>
public static string MakeUniqueFilename(string file, string destinationFolder)
{
string fileName = string.Empty;
try
{
string fileBase = Path.GetFileNameWithoutExtension(file);
string fileExt = Path.GetExtension(file);
fileName = string.Format("{0}{1}", fileBase, fileExt);
string filePath = Path.Combine(destinationFolder, fileName);
int iteration = 1;
while (File.Exists(filePath))
{
fileName = string.Format("{0} ({1}){2}", fileBase, iteration, fileExt);
filePath = Path.Combine(destinationFolder, fileName);
iteration++;
}
}
catch (Exception ex)
{
// Throw up exception to parent
throw new Exception(string.Format("Exception occured in FileHelper.MakeUniqueFilename({0}, {1})", file, destinationFolder), ex);
}
return fileName;
}
public static string GetDefaultExtension(string mimeType)
{
return GetDefaultExtension(mimeType, string.Empty);

Загрузка…
Отмена
Сохранить