Winforms日志记录框架 [英] Winforms logging framework
问题描述
我正在编写WinForms应用程序.我需要将信息记录到文件中.通常,我使用 log4net 进行日志记录,但是由于限制,我无法添加引用.我无法向项目添加外部引用,因为我必须部署单个可执行文件.
I'm writing a WinForms application. I need to log information into a file. Usually I use log4net for logging, but I cannot add the reference, due to a restriction. I cannot add external references to my project, because I must deploy a single executable.
.NET中是否有内置的日志记录框架,因此我可以登录文件而无需添加外部dll?
Is there any built-in logging framework in .NET so I will be able to log into a file without adding an external dll?
P.S:当然,我不想打开一个流并手动编写.
P.S: Of course I don't wanna open a stream and write manually.
推荐答案
是的, System.Diagnostics.TraceListener 类.您需要定义TRACE常数才能使其正常工作,但是可以通过配置app.config来使用许多内置的tracelisteners:
Yes, the System.Diagnostics.TraceListener class. You will need to define the TRACE constant for it to work, but you can use a number of built in tracelisteners, through configuration of your app.config:
- ConsoleTraceListener Class
- EventLogTraceListener Class
- XmlWriterTraceListener Class
- TextWriterTraceListener Class
如果要写入文件,app.config看起来像这样,您还可以添加很多过滤器:
The app.config looks something like this if you want to write to a file, there are a lot of filters you can also add:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="yourName" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\mylogfile.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
和用法:
Trace.TraceError("There's been an error captain: {0}", e);
Trace.TraceWarning("The system broke but don't worry.");
Trace.TraceInformation("Starting up the engines.");
如果可以避免的话,我个人不会写入文本文件,事件日志是一个更好的位置,因为您可以对其进行排序,过滤,自动清除日志并且不会遇到文件锁定问题.
Personally I wouldn't write to a text file if you can avoid it, the Event Log is a better location as you can sort, filter, the logs are auto-purged and you don't get file lock up issues.
这篇关于Winforms日志记录框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!