简体   繁体   English

跟踪 C# 日志详细信息

[英]Trace C# Log Details

Is it possible to write a code to trace a log wrote in c#?.是否可以编写代码来跟踪用 c# 编写的日志? For example:例如:

string filePath = @"C:\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
    writer.WriteLine("Message :" + ex.Message );
}

Now i want to write a code trace exception message (ex.Message) without open Error.txt.(Note: Code should work for trace any website developed in asp.net+c#).现在我想在不打开 Error.txt 的情况下编写代码跟踪异常消息(ex.Message)。(注意:代码应该适用于跟踪任何用 asp.net+c# 开发的网站)。

Of course, there's a powerful built-in mechanism for tracing in .NET platform.当然,.NET 平台有一个强大的内置跟踪机制。 Refer to that and MSDN documentation.请参阅文件和 MSDN 文档。 It's implemented through static classes, so you can use it anywhere in your code.它是通过静态类实现的,因此您可以在代码中的任何位置使用它。 First step is to configure trace listeners via code or .config file:第一步是通过代码或.config文件配置跟踪侦听器:

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

Then, to log a message just call:然后,要记录一条消息,只需调用:

Trace.WriteLine(ex.ToString());

If you just need to check periodically if a certain website is online, you can write something simple like this:如果您只需要定期检查某个网站是否在线,您可以编写如下简单的内容:

Timer t = new Timer(60000);
t.Elapsed += (sender, e) =>
{
    try
    {
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://google.com");
        using (HttpWebResponse httpRes = (HttpWebResponse) httpReq.GetResponse())
        {
            if (httpRes.StatusCode != HttpStatusCode.OK)
            {
                File.AppendAllText(@"C:\Error.txt",
                    string.Format("Server error: {0} {1}",
                     httpRes.StatusCode, httpRes.StatusDescription));
            }
        }
    }
    catch (Exception exc)
    {
        File.AppendAllText(@"C:\Error.txt", "Error: "+exc.ToString());
    }
};
t.Start();

Or use universal monitoring solution like Zabbix.或者使用像 Zabbix 这样的通用监控解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM