我希望在我的应用程序中实现日志记录,但不想使用类似log4net的外部框架。
因此,我想做一些类似DOS的echo输出到文件。最有效的方法是什么?
是否有一种方法可以在不使用外部框架的情况下记录未处理的异常?
我希望在我的应用程序中实现日志记录,但不想使用类似log4net的外部框架。
因此,我想做一些类似DOS的echo输出到文件。最有效的方法是什么?
是否有一种方法可以在不使用外部框架的情况下记录未处理的异常?
public void Logger(string lines)
{
//Write the string to a file.append mode is enabled so that the log
//lines get appended to test.txt than wiping content and writing the log
using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
{
file.WriteLine(lines);
}
}
更多信息请参见MSDN
using
,尽管它是方法本地的,但会很快被释放。 - markmnlfile.WriteLine(lines);
抛出异常时,代码将永远不会运行file.Close();
。使用using
语句块相当于try { // using block } finally { // Dispose }
语句块。这意味着即使在using
语句块内部的代码抛出异常,对象也会被处理并释放。 - Memet Olsen我宁愿不使用类似log4j.net这样的外部框架。
为什么呢?Log4net可能已经满足了您的大部分需求,例如请查看此类:RollingFileAppender。
Log4net有很好的文档,并且在网络上有成千上万的资源和用例。
下面是 MSDN 提供的示例:
using System;
using System.Diagnostics;
using System.Threading;
class MySample{
public static void Main(){
// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
}
}
如果您正在寻找一种真正简单的记录方式,您可以使用这个一行命令。如果文件不存在,则会创建该文件。
System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");
在我发现ELMAH之前,我曾经自己编写错误日志记录。但是我从未像ELMAH那样完美地解决邮件发送问题。
如果你想要自定义错误日志,你可以轻松地编写自己的代码。我将给您展示我的某个项目中的一小段代码。
public void SaveLogFile(object method, Exception exception)
{
string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
try
{
//Opens a new file stream which allows asynchronous reading and writing
using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
{
//Writes the method name with the exception and writes the exception underneath
sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
sw.WriteLine(exception.ToString()); sw.WriteLine("");
}
}
catch (IOException)
{
if (!File.Exists(location + @"log.txt"))
{
File.Create(location + @"log.txt");
}
}
}
q
是捕获的异常)SaveLogFile(MethodBase.GetCurrentMethod(), `q`);