什么是写入事件日志条目的最好方法?目的、事件、方法、日志

2023-09-02 10:35:48 作者:言不由衷

我最近在一个窗口服务的部署过程中出现了问题。四台电脑并没有引起任何问题,但在第五任何尝试启动该服务失败,原因是一个例外。异常堆栈跟踪写入到事件日志,所以我虽然它应该很容易找出原因:

I recently had a problem during the deployment of a windows service. Four computers did not cause any problems, but on the fifth any attempt to start the service failed due to an exception. The exception stack trace is written to the event log, so I though it should be easy to identify the cause:

protected override void OnStart(string[] args)
{
    EventLog.WriteEntry("Starting service", EventLogEntryType.Information);

    try
    {
        //...
        base.OnStart(args);
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry("Service can not start. Stack trace:" + ex.StackTrace, EventLogEntryType.Error);
        Stop();
        return;
    }

    EventLog.WriteEntry("Service started", EventLogEntryType.Information);           
}

但很可惜,没有信息曾被写入日志。我终于追查到被写入第一个日志条目。它抛出一个异常,因为应用程序事件日志已满最近的条目,并配置为7天以上只覆盖项。

But alas, no information was ever written to the log. I finally traced it to the first log entry being written. It threw an exception because the application event log was full with recent entries, and configured to only overwrite entries older than 7 days.

什么是对写入事件日志,考虑到我不能改变应用程序事件日志的配置的最佳实践?

What are the best practices on writing to the event log, considering that I can not change the configuration of the application event log?

我应该始终把 EventLog.WriteEntry 在try块,如果是的话,我应该怎么处理异常(写入到事件日志可能是一个坏主意) ,我应该检查在我的的OnStart 法事件日志状态,或​​者你有什么更好的建议?

Should I always put EventLog.WriteEntry in a try block, if yes, how should I handle the exception (writing it to the event log is probably a bad idea), should I check on the event log status in my OnStart method, or do you have any better suggestion?

推荐答案

我想记录的例外就是你最好吞咽异常的罕见病例之一。在大多数情况下,你不希望你的应用程序,以对这个失败。

I think logging exceptions is one of the rare cases where you are better off swallowing the exception. In most cases you don't want your app to fail on this.

但是,你为什么要编写C自己的日志$ C $呢?使用像NLOG或log4net的框架!这些也吞下例外就像我刚才说的,但你可以重定向日志输出到不同的位置(文件,消息框等),只需配置更改。这使解决这类问题要容易得多。

But why are you writing your logging code yourself anyway? Use a framework like NLog or Log4Net! These also swallow exceptions like I just said but you can redirect the logging output to a different location (file, messagebox etc.) with just a configuration change. This makes solving problems like this much easier.

 
精彩推荐
图片推荐