1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

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

This commit is contained in:
Uncled1023 2017-01-18 14:36:44 -08:00
parent da96fa7f63
commit fc08678d7d
7 changed files with 210 additions and 67 deletions

View File

@ -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

View File

@ -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);
}
}
}

View File

@ -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 */ }
}
}
}

View File

@ -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 */ }
}
}
}

View File

@ -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>

View File

@ -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";
}
}

View File

@ -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
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);