我正在创建一个Windows服务.当发生异常时,我会适当地处理它并创建一个日志.我正在使用装饰器模式,因为人们会看到这些日志的方式有很多种.我有一个电子邮件记录器,一个文件记录器和一个Windows事件记录器,它们都是从LoggingDecorator继承的,它实现了ILogger.因此,没有记录器知道任何其他记录器.
我的问题是:我应该如何处理日志记录异常?
如果写入文件失败,或发送电子邮件失败,我该怎么办?我想用其他记录器记录初始日志内容,但是如何处理日志记录异常呢?它不依赖于构造函数中记录器的顺序吗?
现在,我只是使用空catch(Exception)语句来包装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;
BobbyShaftoe.. 6
如果记录器失败,为什么不将它放在实际的Windows事件日志中?
如果记录器失败,为什么不将它放在实际的Windows事件日志中?