执行错误记录的简单方法? [英] Simple way to perform error logging?

查看:73
本文介绍了执行错误记录的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个小型C#winforms应用程序,作为一项附加功能,我正在考虑向其中添加某种形式的错误记录.有人对如何解决此问题有任何建议吗?这是我以前从未尝试将其添加到以前的项目中的功能,因此,我欢迎来自具有更多经验的开发人员的建议.

I've created a small C# winforms application, as an added feature I was considering adding some form of error logging into it. Anyone have any suggestions for good ways to go about this? This is a feature I've never looked into adding to previous projects, so I'm open to suggestions from Developers who have more experience.

我正在考虑将异常写入指定的文本文件或数据库表中.此应用程序将使用几个月,然后在完成较大产品后将其丢弃.

I was considering something along the lines of writing exceptions to a specified text file, or possibly a database table. This is an application that will be in use for a few months and then discarded when a larger product is finished.

推荐答案

由于您的日志记录需求很简单,因此我不会在外部库上进行过多研究.

I wouldn't dig too much on external libraries since your logging needs are simple.

.NET Framework已经在名称空间System.Diagnostics中附带了此功能,您只需在

.NET Framework already ships with this feature in the namespace System.Diagnostics, you could write all the logging you need there by simply calling methods under the Trace class:

Trace.TraceInformation("Your Information");
Trace.TraceError("Your Error");
Trace.TraceWarning("Your Warning");

然后在app.config文件中配置所有满足您需要的跟踪侦听器:

And then configure all the trace listeners that fit your needs on your app.config file:

<configuration>
  // other config
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
        <add name="textWriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="YourLogFile.txt"/>
        <add name="eventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="YourEventLogSource" />
        <remove name="Default"/>
      </listeners>
    </trace>
  </system.diagnostics>
  // other config
</configuration>

或者,如果您愿意,还可以在应用程序中配置侦听器,而无需依赖配置文件:

or if you prefer, you can also configure your listeners in your application, without depending on a config file:

Trace.Listeners.Add(new TextWriterTraceListener("MyTextFile.log"));

请记住将Trace.AutoFlush属性设置为true,以使文本日志正常工作.

Remember to set the Trace.AutoFlush property to true, for the Text log to work properly.

这篇关于执行错误记录的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆