C# TraceListener 跟踪监听实用示例

原文地址:http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/


Create a Logger using the Trace Listener in C#

by DAVE

in FILES AND DIRECTORIESTUTORIALS

When writing software for the commercial world it is crucial your application can log errors, be it to the database, or to a text file, or even to the Windows Event Log if necessary. The .NET Framework contains a mechanism called a Trace Listener. This Listener is an object which directs the trace output to an appropriate target, such as an error log for example.

In this article I am going to show you how to use the Trace Listener to record your application’s errors to an error log.

To begin this example create a console application and add an App.config file to your project. We are going to use the App.config file to tell our application that it should create a trace listener on start-up. Amend the XML code of your App.config file to look like the below example.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="application.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

As you can see, we are adding a listener of type System.Diagnostics.TextWriterTraceListenerwhich is set to write to a log file called application.log. Also note that in the <trace> node we are setting the autoflush attribute to true. When set to true this attribute tells the listener to flush the buffer after every write operation. For this example it is great but for real world applications you probably would want to set this to false to limit disk read and write operations.

Now in your static Main method you can write to the log using the Trace class as shown below.

static void Main(string[] args)
{
    Trace.WriteLine("Application started.", "MyApp");

    Trace.WriteLine("working...", "MyApp");

    Trace.WriteLine("Application finished.", "MyApp");
}

If we open the application.log file created automatically by the listener right after we run the above code we will find the following in the file:

MyApp: Application started.
MyApp: working...
MyApp: Application finished.

As you can see it’s quite easy to write to the log file. We didn’t even have to open a FileStream to write to the file because it was all done for us automatically by the listener.

This logger we just created is quite crude since we are not recording the date and time of the error, nor are we recording the source. So let’s extend the concept a little by creating a small logger class as shown below.

using System;
using System.Diagnostics;

public static class Logger
{
    public static void Error(string message, string module)
    {
        WriteEntry(message, "error", module);
    }

    public static void Error(Exception ex, string module)
    {
        WriteEntry(ex.Message, "error", module);
    }

    public static void Warning(string message, string module)
    {
        WriteEntry(message, "warning", module);
    }

    public static void Info(string message, string module)
    {
        WriteEntry(message, "info", module);
    }

    private static void WriteEntry(string message, string type, string module)
    {
        Trace.WriteLine(
                string.Format("{0},{1},{2},{3}",
                              DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                              type,
                              module,
                              message));
    }
}

The above Logger class has four public static methods – WarningInfo, and an overloaded Errormethod. Each of these methods calls the private WriteEntry method which actually writes to the log through the Trace class. As you can see here we are writing the date and time, the entry type (“error”“warning”, or “info”), the module where the error occurred, and the actual error message.

Now to use this class we can do the following:

static void Main(string[] args)
{
    try
    {
        Logger.Info("Application started.", "MyApp");
        Logger.Info("working...", "MyApp");
        Logger.Warning("Application about to exit!", "MyApp");
        Logger.Info("Application finished.", "MyApp");

        throw new Exception();
    }
    catch (Exception ex)
    {
        Logger.Error(ex, "MyApp");
    }
}

The above code would produce the following log:

2009-09-16 23:02:04,info,MyApp,Application started.
2009-09-16 23:02:04,info,MyApp,working...
2009-09-16 23:02:04,warning,MyApp,Application about to exit!
2009-09-16 23:02:04,info,MyApp,Application finished.
2009-09-16 23:02:04,error,MyApp,Exception of type 'System.Exception' was thrown.

And there you have it – you now know how to use the Trace Listener in C# and how to create a simple logger class. Obviously the Logger class we created can be enhanced a lot more. For example you could add code to wrap the log file after it grows to 5MB. You could also add code to log the thread which the error occurred on. There is a large number of amendments you could do to make this class better.

I hope you enjoyed this article. Feel free to leave any comments below or if you want you can contact me through my contact page. Also, if you haven’t already subscribed to my rss feed, please do so – Grab RSS Feed.

Dave

 

{ 29 comments… read them below or add one }

David  July 28, 2010 at 22:04

Perfect example for what I needed. Good and consise explaination too. Thanks!

REPLY

  Dave  July 28, 2010 at 22:28

Glad you found this helpful.

REPLY

Allan Pedersen  August 11, 2010 at 06:59

Hi! Great site, great tutorial, it really explained it alle very well… I can only hope for a follow-up on this tracing subject. I would like to have your thoughts about how you would handle the trace log once the software is published…

Thanks again! I will be looking into your site from time to time from now on… :-)

REPLY

  Dave  August 11, 2010 at 20:33

Thanks for your comment. I’m glad you found the tutorial helpful.

I usually handle the trace log in two different ways depending on the application. If the application writes massive amounts of logs to the trace file I would create a new file each day, and then either compress them or archive them every month or so. If the application only writes errors to the log file I would start a new file after it reaches about 5Mb and then archive those every year. It really depends on how much your application will be writing to the log file.

REPLY

Allan Pedersen  August 13, 2010 at 16:03

What is your best practise for retrieving the log files? I like to get the log files whin an error occurs so I am sending them to my self by mail from the program…

REPLY

  Dave  August 13, 2010 at 21:47

Usually I do the same. When sending errors by email you will immediately know when something goes wrong, and it’s quite simple to implement and works most of the time.

I have also worked on systems where error logs are automatically downloaded from our clients’ servers over ftp on a weekly basis. Also, what you could do instead of sending emails is open a socket from the client’s pc to your server and send the error message over tcp. Then you could store it in a database on your server, but this does require you to have a server with a static ip always online.

I am sure there are other methods worth exploring, but if you are not expecting many errors and only have a few installations of your application out there, I would stick with receiving errors by email. I would create an email account just for this purpose though, so as not to clutter my personal mailbox.

REPLY

Allan Pedersen  August 13, 2010 at 21:53

Thanks, good to hear i am not way of track by mailing myself error/log reports… :-) (My company is not that big and installations is relatively limited). Logging everything to a database might be a bit to heavy net usage for my liking.

Thanks again for your tutorial and for your comments….

REPLY

xiaokang  March 25, 2011 at 12:43

Very good!Very Helpful!
If want to ad date information in log, can add this config:

but ,log will by large.
i want to close trace output when not necessary ,how can i do?
thank you!

REPLY

  Sanjeet  August 11, 2011 at 16:22

Nice article a better way to explain..

REPLY

redcode  February 15, 2012 at 03:50

nice tutorial, could you please show how to store information in a database ??
thank you,
Bob

REPLY

Patel Rikin  April 6, 2012 at 21:00

thanks a lot…..

nice article …. i things this one best article…….

i m lot of search but this article whatever explain it very quickly understandable……..

REPLY

Gupreet  April 17, 2012 at 19:38

Very nice article. Nice concise and to the point.

REPLY

TheClever  April 30, 2012 at 02:48

Hello,
I did not success. I did what you said but I can see the application.log
What can be the problem?
I am using SharpDeveloper,
Thanks

REPLY

TheClever  April 30, 2012 at 03:08

Ok, I test it on VS 2010 Express and it workss vey well. Thanks.
But now how can I customized to write the log file to a specific directory for example. I want the application.log file to be store in the Log directory:

It does not create anything, no log directory
How can I set it?
Thanks

REPLY

Fraz  September 14, 2012 at 00:23

Nice article! Got 2 questions though.

Can u specify which file it writes to at run time?

How would u turn the logging off? would u just comment out ?

REPLY

Philip Wade  January 4, 2013 at 03:02

After trawling through a dozen or more ‘tutorials’, I found this one which explains Trace logging clearly, concisely, and has an example that works. Splendid.

REPLY

mcartur  January 4, 2013 at 21:47

This is exactly was I was looking for¡¡ Simple and clear.

Thanks a lot¡¡

REPLY

samashti  February 11, 2013 at 21:47

I did as you said ,but no log file as been generated as such..
What could be the problem?
Plz help me..

REPLY

Sonam Kumar  February 25, 2013 at 20:17

Thank you so much! Just what I wanted and you explained to so well. Sweet!

REPLY

Rakesh  March 29, 2013 at 06:42

neatly written and clearly explained, this is how articles should be written

REPLY

  Sukumar Jena  June 12, 2013 at 20:08

You have remarkable information on this web-site.
Thanks for sharing here

REPLY

suresh  June 28, 2013 at 17:41

Its a Good Information and much useful one can u help me with the answer for this ( how can I customized to write the log file to a specific directory) ?

REPLY

Chetan  July 3, 2013 at 20:46

How can we create .log files daily basis ?

REPLY

Sean  September 26, 2013 at 21:47

Why write your own methods here when they are provided…

you created a class for these methods

public static void Error(string message, string module)
public static void Error(Exception ex, string module)
public static void Warning(string message, string module)
public static void Info(string message, string module)

When you could just use…

Trace.TraceInformation(string message)
Trace.TraceWarning(string message)
Trace.TraceError(string message)

this also means you would not have to include the class you wrote.

REPLY

  Dave  September 29, 2013 at 21:44

Hi Sean – thanks for your comments. When I wrote this article I wasn’t aware of the built in .NET methods you mentioned and that’s why I wrote my own. I should probably update my article to mention this – thanks for pointing that out.

REPLY

Bud  October 1, 2013 at 08:35

One little fact I don’t see mentioned in the article, where does the ‘application.log’ reside?

REPLY

  Dave  October 4, 2013 at 13:45

Hi Bud – the log is written where you specify in the App.config file, however in this example it’s in the directory where the application is running from (the bin folder).

REPLY

xarkam  October 24, 2013 at 23:16

Hello,

it’s possible to have one log file per day ?

REPLY

Jay  April 25, 2014 at 21:31

Thank you! it was very useful :)

REPLY

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值