是否可以编写代码来跟踪在c#中写入的日志? 例如:
string filePath = @"C:\Error.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message );
}
现在我想编写代码跟踪异常消息(ex.Message)而不打开Error.txt。(注意:代码应该用于跟踪在asp.net + c#中开发的任何网站。)
答案 0 :(得分:2)
当然,在.NET平台中有一个强大的内置跟踪机制。请参阅that和MSDN文档。它是通过静态类实现的,因此您可以在代码中的任何位置使用它。
第一步是通过代码或.config
文件:
Trace.Listeners.Add(new TextWriterTraceListener("trace.log");
然后,要记录消息,请致电:
Trace.WriteLine(ex.ToString());
如果您只是需要定期检查某个网站是否在线,您可以编写如下简单的内容:
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();
或使用像Zabbix这样的通用监控解决方案。