gpt4 book ai didi

c# windows-services - 如何处理日志记录异常?

转载 作者:行者123 更新时间:2023-11-30 20:14:34 25 4
gpt4 key购买 nike

我正在创建 Windows 服务。当异常发生时,我会适本地处理它并创建一个日志。我正在使用 decorator pattern ,因为人们会以多种不同的方式查看这些日志。我有一个电子邮件记录器、一个文件记录器和一个 Windows 事件记录器,它们都继承自实现 ILogger 的 LoggingDecorator。因此,没有记录器知道任何其他记录器。

我的问题是:我应该如何处理日志异常?

如果写入文件失败,或者发送邮件失败,我该怎么办?我想用其他记录器记录初始日志内容,但是我该如何处理日志记录异常?它不也取决于构造函数中记录器的顺序吗?

现在,我只是用空的 catch(Exception) 语句包装 try/catch block ,这感觉很脏,让 FxCop 对我大喊大叫。但是,这是其中之一吗 "it depends"时刻?

[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;

最佳答案

如果记录器失败,为什么不将其放入实际的 Windows 事件日志中?

关于c# windows-services - 如何处理日志记录异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/345656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com