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


92

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

因此,我想做类似DOS 对文件的回显。最有效的方法是什么?

有没有办法在不使用外部框架的情况下记录未处理的异常?


1
您可以使用内置的System.Diagnostics.TraceSource。<br>这是内置的跟踪侦听器 + FileLogTraceListener的列表。有很多的手册在网上这样,[或这一个杰夫阿特伍德](codinghorror.com/blog/2005/03/logging-tracelistener
HuBeZa

2
我觉得企业库比log4net更好。
hungryMind 2011年

如果您只是在寻找简单的控制台日志记录,那么System.Diagnostics.Tracing可能适合您。可以像Console(Trace.WriteLine)一样使用Trace。
保罗

Answers:


66
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


22
您应该使用using文件上的文件,尽管由于它是方法的本地文件,所以无论如何都会很快消失。
markmnl 2014年

19
另外请记住,当file.WriteLine(lines);引发异常时,代码将永远不会命中file.Close();。使用using等同于try { // using block } finally { // Dispose }。这意味着即使该using块内的代码引发异常,该对象也将被处置,
Memet Olsen

6
如果在记录完成之前再次调用此方法怎么办?您将引发一个错误-该进程无法访问文件'C:\ test.txt',因为该文件正在被另一个进程使用。有人知道这个问题吗?
Mike Sportsman

23

我宁愿不使用任何外部框架,例如log4j.net。

为什么?Log4net可能会满足您的大多数需求。例如,检查此类:RollingFileAppender

Log4net有充分的文档记录,并且Web上有成千上万的资源和用例。


3
原因是我从未在.net中使用过任何外部库,所以我首先需要学习如何使用它;)
IAdapter

4
只需添加对您的项目的引用并放置一些xml配置-确实很容易。Google for log4net教程,然后选择最适合您的教程。
empi 2011年

23
使用Nuget。使用外部图书馆将变得轻而易举
heneryville'Mar

36
为什么这么多投票?该问题两次声明OP不想使用外部框架,并明确提到不希望使用Log4net。当然这应该是评论,而不是答案?
RyanfaeScotland,2015年

9
@RyanfaeScotland是的,也许它不适合OP,但是请不要忘记这是一个公共站点。由于问题的标题仅注明“如何使用c#登录”,因此像我一样擅长使用任何库的人也将登陆此处,并找到此答案有用。实际上,当我用Google搜索“ c#日志记录”时,该线程是第一个结果。
swenzel

18

您可以直接写入事件日志。检查以下链接:
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.");

    }
}

1
在不同的类中使用相同的EventLog的最佳实践是什么?将其作为参数传递给构造函数?从单例类静态访问它?还是更好?
dpelisek

15

如果您正在寻找一种真正简单的日志记录方法,则可以使用这种衬管。如果文件不存在,则创建它。

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

该解决方案的问题在于它增加了IO操作。因此,不建议使用它来记录批处理算法操作
Rami Yampolsky

@RamiYampolsky,我不明白你的意思。
dan-gph

@ dan-gph如果您实现一些执行大量CPU操作的代码,则在这段代码中记录日志的情况下,您“浪费”了一些时间用于记录日志,而不是尝试执行的实际算法。因此,您希望尽可能地“浪费”时间。像上面的示例中那样进行IO操作确实很长,因此,如果您的代码中包含许多日志记录命令,则可能会使整个执行速度慢1000倍!
Rami Yampolsky

@RamiYampolsky,我刚刚使该代码循环了100,000次,花了10秒钟。因此,这是每秒10,000个日志条目,即每个条目0.01微秒。如果您在一秒钟内记录了10件事,那将花费0.1微秒。所以不,那根本就没有太多的开销。
dan-gph

@ dan-gph我的答案与不同的用例有关。尝试执行100,000次循环以简化计算,只求和+ = i,然后执行日志。试试看有无日志
Rami Yampolsky

7

在发现ELMAH之前,我常常编写自己的错误日志记录。我从来没有像ELMAH那样完美地完成过邮件发送工作。


我会看一下,出于我的推理,请查看我的empi的评论。
IAdapter 2011年

ELMAH非常直截了当,甚至没有什么好笑的,您可以从字面上将其放入Web配置中添加几行即可使用。
jonezy 2011年

另外,就您了解应用程序何时开始/开始崩溃的要求而言,我发现elmah比大多数其他应用程序要好,因为它能够发送电子邮件,因此只要服务器启动,您就会收到来自以下服务器的错误电子邮件埃尔玛
jonezy 2011年

6

如果您想靠近.NET,请查看Enterprise Library Logging Application Block。看这里。或快速入门教程,请检查。我使用了Enterprise Library中的Validation应用程序Block,它非常适合我的需求,并且非常容易在您的项目中“继承”(安装并引用它!)。


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

7
您知道当文件尚不存在时会错过第一个条目吗?
oɔɯǝɹ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.