简体   繁体   English

如何将错误日志或异常写入C#.NET中的文件

[英]How to write error log or exception into file in C#.NET

I need help in writing error into separate text file and Email that file to me. 我需要帮助将错误写入单独的文本文件并将该文件通过电子邮件发送给我。 Actually, I had created windows application but I didn't add any exception or writing error into separate file. 实际上,我已经创建了Windows应用程序,但是没有添加任何异常或将错误写入单独的文件中。 Now, I want whenever my application is interrupted because of any error then error should be noted into separate text file and that file should be email to me. 现在,我希望每当我的应用程序由于任何错误而中断时,都应将错误记录到单独的文本文件中,并且该文件应通过电子邮件发送给我。

I did research on error log file and all I found that create separate Class for writing Error Log into text file and call that file into try-catch block of all the methods. 我对错误日志文件进行了研究,发现所有这些都创建了单独的类,用于将错误日志写入文本文件,然后将该文件调用到所有方法的try-catch块中。 But my program/application has grown vast and I need to add intermediate of it. 但是我的程序/应用程序已经变得越来越庞大,我需要在其中添加中间内容。 Also, I found about log4net but still it works in same manner. 此外,我发现了有关log4net的信息,但仍然可以相同的方式工作。

Can anyone guide me how to write error log at application level or when application get any error message? 谁能指导我如何在应用程序级别或在应用程序收到任何错误消息时编写错误日志?

Thanks for help. 感谢帮助。

If you are not attached to any system already, I'd suggest you look at log4net , since it will do what you're asking for, way, way, more, and is a popular library so it will be recognizable and extensible by other professionals on your team. 如果您尚未连接到任何系统,建议您查看log4net ,因为它可以满足您的要求,方式,方式等等,并且是一个受欢迎的库,因此其他人可以识别和扩展它。您团队中的专业人士。 Also since someone else maintains it you will occasionally get free bug fixes. 另外,由于其他人对此进行了维护,因此您偶尔会获得免费的错误修复。

As far as I can see, all you need is to handle AppDomain.UnhandledException Event . 据我所知,您只需要处理AppDomain.UnhandledException Event即可 It will give you most common information about crash. 它会为您提供有关崩溃的最常见信息。 You can use it to start the research of crash reasons. 您可以使用它来开始研究崩溃原因。

And of course in the UnhandledException handler you can use whatever you want, log4net or custom logger. 当然,在UnhandledException处理程序中,您可以使用任何所需的log4net或自定义记录器。

try 尝试

Log4Net Log4Net

Smtp Logger: Smtp记录器:

<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<smtpHost value="SMTPServer.domain.com" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
</layout>

要在其他地方未捕获的所有地方处理所有异常,请考虑为Application.ThreadException实现处理程序

I created a logging helper that I use for my WPF project. 我创建了用于WPF项目的日志记录帮助程序。 This is a large project with many different components. 这是一个包含许多不同组件的大型项目。 This was before I learned how to work with MVVM so please excuse if this breaks the pattern. 这是在我了解如何使用MVVM之前,因此请原谅这会破坏模式。 This system is continuously expanding with new components to handle different tasks. 该系统正在不断扩展以新组件来处理不同的任务。 You can think of a component as a standalone unit which handles a specific task, with the Main Component being the master of them all. 您可以将组件视为处理特定任务的独立单元,而“主要组件”是所有组件的主组件。 This logging allowed us to log errors no matter in which component they occurred. 此日志记录使我们可以记录错误,无论它们发生在哪个组件中。 It may be an overkill, but worked very well for us. 这可能是一个矫kill过正,但对我们来说效果很好。

I am using the same principle to log all system wide events (User Actions, Data Changes..etc) 我使用相同的原理记录所有系统范围的事件(用户操作,数据更改等)。

In my App.xaml.cs I catch all unhandled errors. 在我的App.xaml.cs中,我捕获了所有未处理的错误。 Note that this is last resort of logging, I use try catch wherever I would expect exceptions to occur (db connections for example). 请注意,这是记录日志的最后手段,无论我希望发生异常的地方(例如数据库连接),我都会使用try catch。

public partial class App : Application
{
    void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        ErrorEvent errorEvent = new ErrorEvent();
        errorEvent.LogErrorEvent(e.Exception);
        e.Handled = true;
    }
}

ErrorEvent is a class within my Utilities dll that uses Event Routing to log the errors. ErrorEvent是我的实用程序dll中的类,该类使用事件路由记录错误。 I have different type of errors, depending on severity. 根据严重性,我有不同类型的错误。 All these errors are logged into a database, and the only component aware of the database connections is the main one. 所有这些错误都记录到数据库中,并且唯一知道数据库连接的组件是主要的组件。 This is why I use Routing Event to send the exception to the Main Component to be logged. 这就是为什么我使用路由事件将异常发送到要记录的主组件的原因。 The ErrorEventHelper gets populated and routed to the Main Component. ErrorEventHelper被填充并路由到主要组件。 In situations where I am using try catches, I create the EventHelper and pass it to be logged using LogErrorEvent method. 在使用try catch的情况下,我将创建EventHelper并将其传递给使用LogErrorEvent方法进行记录。 The ShowMessage property is used to decide if the user will be inform of the exception, or if it will only be logged. ShowMessage属性用于确定是否将异常通知用户,或者仅记录该异常。

public class ErrorEvent : UserControl
{
    public delegate void ErrorEventEventHandler(object sender, RoutedCustomEventArgs e);

    public static readonly RoutedEvent EventOccuredEvent = EventManager.RegisterRoutedEvent(
    "EventOccured", RoutingStrategy.Bubble, typeof(ErrorEventEventHandler), typeof(ErrorEvent));

    // Provide CLR accessors for the event
    public event RoutedEventHandler EventOccured
    {
        add { AddHandler(EventOccuredEvent, value); }
        remove { RemoveHandler(EventOccuredEvent, value); }
    }

    public void LogErrorEvent(ErrorEventHelper occuredEventDetails)
    {
        RoutedEventArgs newEventArgs = new RoutedCustomEventArgs(ErrorEvent.EventOccuredEvent, occuredEventDetails);
        RaiseEvent(newEventArgs);
    }

    public void LogErrorEvent(Exception exception)
    {
        ErrorEventHelper occuredEventDetails = new ErrorEventHelper();
        occuredEventDetails.ErrorType = ErrorEventHelper.EventTypes.Critical;
        occuredEventDetails.ErrorValue = exception.Message;
        occuredEventDetails.ErrorStack = exception.StackTrace;
        occuredEventDetails.ShowMessage = true;

        RoutedEventArgs newEventArgs = new RoutedCustomEventArgs(ErrorEvent.EventOccuredEvent, occuredEventDetails);
        RaiseEvent(newEventArgs);

        if (exception.InnerException != null)
        {
            LogErrorEvent(exception.InnerException);
        }
    }

    public class RoutedCustomEventArgs : RoutedEventArgs
    {
        public ErrorEventHelper OccuredEventDetails { get; private set; }

        public RoutedCustomEventArgs(RoutedEvent routedEvent, ErrorEventHelper occuredEventDetails)
            : base(routedEvent)
        {
            this.OccuredEventDetails = occuredEventDetails;
        }
    }

}

public class ErrorEventHelper
{
    public string ErrorValue { get; set; }
    private EventTypes _ErrorType = EventTypes.Critical;
    public EventTypes ErrorType 
    {
        get
        {
            return _ErrorType;
        }
        set
        {
            _ErrorType = value;
        }
    }
    public string ErrorStack { get; set; }
    public bool ShowMessage { get; set; }

    public enum EventTypes
    {
        Critical,
        Warning,
        Information
    }

    public void SendMessage()
    {
        ErrorEvent newEvent = new ErrorEvent();
        newEvent.LogErrorEvent(this);
    }
}

In the MainWindow I register the event handler. 在MainWindow中,我注册了事件处理程序。

EventManager.RegisterClassHandler(typeof(ErrorEvent),
                        ErrorEvent.EventOccuredEvent, new ErrorEvent.ErrorEventEventHandler(LogOccuredErrors));

And finally handle it: 最后处理:

private void LogOccuredErrors(object sender, ErrorEvent.RoutedCustomEventArgs e)
{
     ErrorEventHelper eventHelper = e.OccuredEventDetails;

 //Call Database Helper to log to database or output to file and email
    StringBuilder builder = new StringBuilder();
    builder.AppendLine(eventHelper.ErrorType);
    builder.AppendLine(eventHelper.ErrorValue);
    builder.AppendLine(eventHelper.ErrorStack);
    if (eventHelper.ShowMessage)
    {
        MessageBox.Show(eventHelper.ErrorValue);
    }

//Create your log file and email it
    File.WriteAllText(@"C:\log.txt", ControllerBuilder.ToString())
//email here

}

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

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