Explorar el Código

Added try/catch wrappers around the logging to handle exceptions that shouldn't be tracked.

tags/2.0.6
Teknikode hace 4 años
padre
commit
eceb9f22ab
Se han modificado 1 ficheros con 72 adiciones y 67 borrados
  1. 72
    67
      Utilities/Logging/Logger.cs

+ 72
- 67
Utilities/Logging/Logger.cs Ver fichero

@@ -12,15 +12,7 @@ namespace Teknik.Logging
{
public static class Logger
{
private static object Locker = new object();

private static Config m_Config
{
get
{
return Config.Load();
}
}
private static readonly object Locker = new object();

public static void WriteEntry(string message)
{
@@ -50,99 +42,112 @@ namespace Teknik.Logging
log.Message = message;
log.Exception = exception;

WriteEntry(log);
WriteLogMessage(log);
}

public static void WriteEntry(LogMessage log)
private static void WriteLogMessage(LogMessage log)
{
if (m_Config.LoggingConfig.Enabled)
try
{
// 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)
Config config = Config.Load();
if (config.LoggingConfig.Enabled)
{
// Lock the file processing so only 1 thread is working on the log file at a time
lock (Locker)
{
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);
// Do we want to write a log for this level? (Default to Error)
LogLevel minLogLevel = LogLevel.Error;
Enum.TryParse(config.LoggingConfig.EmailLevel, out minLogLevel);

if (File.Exists(logFile))
try
{
if (log.Level >= minLogLevel)
{
// File already exists, so lets see if we need to rotate it
if (m_Config.LoggingConfig.RotateLogs)
// Lock the file processing so only 1 thread is working on the log file at a time
lock (Locker)
{
FileInfo info = new FileInfo(logFile);
if (m_Config.LoggingConfig.MaxSize < info.Length && m_Config.LoggingConfig.MaxSize > 0)
if (!Directory.Exists(config.LoggingConfig.OutputDirectory))
{
// 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);
Directory.CreateDirectory(config.LoggingConfig.OutputDirectory);
}
// Get current log file
string fileName = Constants.LOG_FILE_NAME_PREFIX + Constants.LOG_FILE_EXT;
string logFile = Path.Combine(config.LoggingConfig.OutputDirectory, fileName);

// 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)
if (File.Exists(logFile))
{
// We will have too many logs, so let's remove the last one
totalFiles.Sort();
string fileToRemove = totalFiles[totalFiles.Count - 1];
File.Delete(fileToRemove);
// File already exists, so lets see if we need to rotate it
if (config.LoggingConfig.RotateLogs)
{
FileInfo info = new FileInfo(logFile);
if (config.LoggingConfig.MaxSize < info.Length && 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, config.LoggingConfig.OutputDirectory);
string newLog = Path.Combine(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(config.LoggingConfig.OutputDirectory, string.Format("{0}*{1}", Constants.LOG_FILE_NAME_PREFIX, Constants.LOG_FILE_EXT), SearchOption.TopDirectoryOnly).ToList();
if (totalFiles.Count + 1 > config.LoggingConfig.MaxCount && 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() + Environment.NewLine);
}
}

// We have rotated if needed, so let's write the entry
File.AppendAllText(logFile, log.ToString() + Environment.NewLine);
}
}
catch (Exception) { } // If we throw when writing the log, still try to send the email if needed

// 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)
// Send Email Message if enabled
if (config.LoggingConfig.SendEmail)
{
string subject = string.Format("{0} Log Message", log.Level);
string message = "Message: " + log.Message;
if (log.Exception != null)
// Do we want to send an email for this level? (Default to error)
LogLevel minEmailLevel = LogLevel.Error;
Enum.TryParse(config.LoggingConfig.EmailLevel, out minEmailLevel);
if (log.Level >= minEmailLevel)
{
message += Environment.NewLine + Environment.NewLine + "Exception: " + log.Exception.GetFullMessage(true, true);
string subject = string.Format("{0} Log Message", log.Level);
string message = "Message: " + log.Message;
if (log.Exception != null)
{
message += Environment.NewLine + Environment.NewLine + "Exception: " + log.Exception.GetFullMessage(true, true);
}
SendErrorEmail(subject, message);
}
SendErrorEmail(subject, message);
}
}
}
catch (Exception)
{
// Can't do anything about it. :/
}
}

private static void SendErrorEmail(string subject, string message)
{
try
{
Config config = Config.Load();
// 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.Host = config.LoggingConfig.SenderAccount.Host;
client.Port = config.LoggingConfig.SenderAccount.Port;
client.EnableSsl = 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.Credentials = new System.Net.NetworkCredential(config.LoggingConfig.SenderAccount.Username, config.LoggingConfig.SenderAccount.Password);
client.Timeout = 5000;

MailMessage mail = new MailMessage(m_Config.LoggingConfig.SenderAccount.EmailAddress, m_Config.LoggingConfig.RecipientEmailAddress);
MailMessage mail = new MailMessage(config.LoggingConfig.SenderAccount.EmailAddress, config.LoggingConfig.RecipientEmailAddress);
mail.Subject = subject;
mail.Body = message;
mail.BodyEncoding = UTF8Encoding.UTF8;

Cargando…
Cancelar
Guardar