我正在创建一个Windows服务。当出现异常时,我会适当地处理它并创建日志。我使用装饰器模式,因为有许多不同的方法可以查看这些日志。我有一个电子邮件记录器、一个文件记录器和一个Windows事件记录器,它们都继承自LoggingDecorator,实现了ILogger。因此,没有任何记录器知道其他任何记录器。
我的问题是:我应该如何处理日志记录的异常?
如果写入文件失败或发送电子邮件失败,我应该怎么办?我想与其他记录器一起记录初始日志内容,但我该怎么处理记录异常?这不也取决于构造函数中记录器的顺序吗?
现在,我只是用空try/catch块包装try/catch块,这感觉很不好,并且使FxCop向我发出警告。然而,这是那些“取决于”的时刻之一吗?
[Flags]
public enum LoggingCategories
{
None = 0,
ServiceEvents = 1,
ProcessingInformation = 2,
ProcessingErrors = 4,
UnexpectedErrors = 8
}
public interface ILogger
{
void LogMessage(LoggingCategories category, string message);
}
public abstract class LoggerDecorator : ILogger
{
private ILogger _decoratedLogger;
private LoggingCategories _categories;
protected LoggerDecorator(ILogger logger, LoggingCategories categories)
{
this._decoratedLogger = logger;
this._categories = categories;
}
protected bool ShouldLogCategory(LoggingCategories category)
{
return ((this._categories & category) == category);
}
public virtual void LogMessage(LoggingCategories category, string message)
{
_decoratedLogger.LogMessage(category, message);
}
}
public class ControlLogger : ILogger
{
public ControlLogger()
{
}
public void LogMessage(LoggingCategories category, string message)
{
Console.WriteLine(LoggingHelper.ConstructLog(category, message));
}
}
(WindowsEventLogger中的可疑代码)
try
{
this._eventLog.WriteEntry(log, type);
}
catch (Exception)
{
//Even if this logging fails, we do not want to halt any further logging/processing.
}
(在服务构造函数中的代码)
ILogger controlLogger = new ControlLogger();
ILogger windowsEventLogger = new WindowsEventLogger(controlLogger, windowsEventLogCategories, windowsEventLogSource);
ILogger emailLogger = new EmailLogger(windowsEventLogger, emailCategories, emailSubject, emailAddresses);
ILogger fileLogger = new FileLogger(emailLogger, fileCategories, logDirectory, logFileNamePrefix, logFileExtension);
this._logger = fileLogger;