如何在不使用第三方库的情况下登录C#?

时间:2011-02-20 14:24:03

标签: c# .net winforms performance logging

我想在我的应用程序中实现日志记录,但不希望使用任何外部框架,如log4net。

所以我想像DOS的echo那样对文件做些什么。最有效的方法是什么?

有没有办法记录未使用外部框架记录的未处理异常?

7 个答案:

答案 0 :(得分:62)

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

  System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);
  file.WriteLine(lines);

  file.Close();

}

了解更多信息MSDN

答案 1 :(得分:23)

  

我宁愿不使用任何外部   像log4j.net这样的框架。

为什么呢? Log4net可能会满足您的大多数要求。 例如,请检查此课程:RollingFileAppender

Log4net已有详细记录,网上有数千个资源和用例。

答案 2 :(得分:16)

您可以直接写入事件日志。检查以下链接:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

这是来自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.");

    }
}

答案 3 :(得分:14)

如果您正在寻找一种真正简单的记录方式,您可以使用这一个衬垫。如果该文件不存在,则创建该文件。

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");

答案 4 :(得分:7)

我曾经写过自己的错误记录,直到我发现ELMAH。我从来没有能够像ELMAH那样完美地收到电子邮件部分。

答案 5 :(得分:6)

如果您希望接近.NET ,请查看企业库日志记录应用程序阻止。看here。或者,对于快速入门教程,请检查this。我使用了企业库中的验证应用程序块,它非常适合我的需求,并且非常容易在项目中“继承”(安装它并引用它!)。

答案 6 :(得分:4)

如果您想要自己的自定义错误记录,您可以轻松编写自己的代码。我会从我的一个项目中给你一个片段。

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`);