执行错误记录的简单方法?

时间:2013-12-11 16:59:18

标签: c# .net logging error-handling error-logging

我已经创建了一个小型的C#winforms应用程序,作为一项附加功能,我正考虑在其中添加某种形式的错误记录。任何人都有任何关于这方面的好方法的建议?这是我从未考虑过添加到以前的项目中的功能,所以我愿意接受有更多经验的开发人员的建议。

我正在考虑将异常写入指定文本文件或可能是数据库表的问题。这个应用程序将使用几个月,然后在更大的产品完成时丢弃。

9 个答案:

答案 0 :(得分:81)

由于您的日志记录需求很简单,因此我不会过多地研究外部库。

.NET Framework已在命名空间System.Diagnostics中附带此功能,您只需调用Trace类下的方法即可编写所需的所有日志记录:

Trace.TraceInformation("Your Information");
Trace.TraceError("Your Error");
Trace.TraceWarning("Your Warning");

然后在app.config文件中配置所有符合您需求的跟踪侦听器:

<configuration>
  // other config
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
        <add name="textWriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="YourLogFile.txt"/>
        <add name="eventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="YourEventLogSource" />
        <remove name="Default"/>
      </listeners>
    </trace>
  </system.diagnostics>
  // other config
</configuration>

或者如果您愿意,您也可以在应用程序中配置监听器,而不依赖于配置文件:

Trace.Listeners.Add(new TextWriterTraceListener("MyTextFile.log"));

请记住将Trace.AutoFlush属性设置为true,以使文本日志正常工作。

答案 1 :(得分:10)

在我看来,最佳解决方案是使用NLog:http://nlog-project.org/

只需从NuGet安装配置包:http://www.nuget.org/packages/NLog.Config/,您将最终获得库和预先配置的文件记录器......

然后在您的代码中,您只需要:

// A logger member field:

private readonly Logger logger = LogManager.GetCurrentClassLogger(); // creates a logger using the class name

// use it:
logger.Info(...);
logger.Error(...);

// and also:
logger.ErrorException("text", ex); // which will log the stack trace.

在您获得的配置文件中,您需要取消注释所需的部分:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!-- 
        See http://nlog-project.org/wiki/Configuration_file 
        for information on customizing logging rules and outputs.
    -->
    <targets>
        <!-- add your targets here -->

        <!-- UNCOMMENT THIS!
        <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
                layout="${longdate} ${uppercase:${level}} ${message}" />
        -->
    </targets>

    <rules>
        <!-- add your logging rules here -->

        <!-- UNCOMMENT THIS!
        <logger name="*" minlevel="Trace" writeTo="f" />
        -->
    </rules>
</nlog>

nlog.config文件的属性编辑为

Copy to Output Directory: Copy always

答案 2 :(得分:10)

您可以使用SimpleLog

它是一个简单但强大而强大的一流日志记录解决方案,易于理解,易于集成且易于使用。无需花费数天时间来设置和自定义log4Net,通过该课程,您可以在几分钟内完成。

虽然它当前登录到文件,但它应该可以轻松自定义以登录到数据库。

http://www.codeproject.com/Tips/585796/Simple-Log

答案 3 :(得分:3)

好吧log4net就像一块砖。配置可能有点困难,但值得。它还允许您配置这些日志文件的文件锁定等。

http://www.codeproject.com/Articles/140911/log4net-Tutorial

答案 4 :(得分:2)

下面是log4net的例子:

  1. 创建一个名为Log4NetTest的新控制台项目
  2. 将log4net [1.2.13] nuget包添加到项目
  3. 编写以下程序:

    using System.Threading.Tasks;
    using log4net;
    using System.Text;
    using System.CollectionsGeneric;
    using System;
    namespace Log4NetTest
    {
        class Program
        {
    
            private static readonly ILog _logger = LogManager.GetLogger("testApp.LoggingExample");
    
            static void Main(string[] args)
            {
                // Configure from App.config. This is marked as obsolete so you can also add config into separate config file
                // and use log4net.Config.XmlConfigurator method to configure from xml file.            
                log4net.Config.DOMConfigurator.Configure(); 
    
                _logger.Debug("Shows only at debug");
                _logger.Warn("Shows only at warn");
                _logger.Error("Shows only at error");
    
                Console.ReadKey();
            }
        }
    }
    
  4. 将您的app.config更改为以下内容:

    <!-- language: xml -->
    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
        <configSections> 
            <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 
        </configSections> 
            <startup> 
                    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> 
            </startup> 
        <log4net debug="false"> 
            <appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" > 
                <param name="File" value="myLog.log" /> 
                <param name="AppendToFile" value="true" /> 
                <layout type="log4net.Layout.PatternLayout,log4net"> 
                    <param name="ConversionPattern" value="%date [%thread] %-5level %logger %ndc - %message%newline" /> 
                </layout>      
            </appender> 
            <root> 
                <priority value="ALL" /> 
                <appender-ref ref="LogFileAppender" /> 
            </root> 
            <category name="testApp.LoggingExample"> 
                <priority value="ALL" /> 
            </category> 
        </log4net> 
    </configuration>
    
  5. 5.运行应用程序,您应该从bin \ Debug文件夹中找到以下文件:

    2013-12-13 13:27:27,252 [8] DEBUG testApp.LoggingExample (null) - Shows only at debug
    2013-12-13 13:27:27,280 [8] WARN  testApp.LoggingExample (null) - Shows only at warn
    2013-12-13 13:27:27,282 [8] ERROR testApp.LoggingExample (null) - Shows only at error
    

答案 5 :(得分:1)

您只需将异常错误写入文本文件即可。 Write to Text File。一个建议是将您创建的文件放在userdata或appdata目录中,这样您就不必为权限而烦恼。

由于这仅需要几个月而且将被丢弃,因此没有理由过分使用DB。一个简单的文本文件就足够了。

答案 6 :(得分:1)

创建一个名为Log.cs的类 我正在使用Linq To SQl保存到数据库

    YourClass *yourClassObject = (__bridge YourClass *)(observer);
    [yourClassObject dimScreen];

创建下表

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
public static partial class Log
{
    /// <summary>
    /// Saves the exception details to ErrorLogging db with Low Priority
    /// </summary>
    /// <param name="ex">The exception.</param>
    public static void Save(this Exception ex)
    {
        Save(ex, ImpactLevel.Low, "");
    }

    /// <summary>
    /// Saves the exception details to ErrorLogging db with specified ImpactLevel
    /// </summary>
    /// <param name="ex">The exception.</param>
    /// <param name="impactLevel">The Impact level.</param>
    public static void Save(this Exception ex, ImpactLevel impactLevel)
    {
        Save(ex, impactLevel,"");
    }
    /// <summary>
    /// Saves the exception details to ErrorLogging db with specified ImpactLevel and user message
    /// </summary>
    /// <param name="ex">The exception</param>
    /// <param name="impactLevel">The impact level.</param>
    /// <param name="errorDescription">The error Description.</param>
    public static void Save(this Exception ex, ImpactLevel impactLevel, string errorDescription)
    {
        using (var db = new ErrorLoggingDataContext())
        {
            Log log = new Log();

            if (errorDescription != null && errorDescription != "")
            {
                log.ErrorShortDescription = errorDescription;
            }
            log.ExceptionType = ex.GetType().FullName;
            var stackTrace = new StackTrace(ex, true);
            var allFrames = stackTrace.GetFrames().ToList();
            foreach (var frame in allFrames)
            {
                log.FileName = frame.GetFileName();
                log.LineNumber = frame.GetFileLineNumber();
                var method = frame.GetMethod();
                log.MethodName = method.Name;
                log.ClassName = frame.GetMethod().DeclaringType.ToString();
            }

            log.ImpactLevel = impactLevel.ToString();
            try
            {
                log.ApplicationName = Assembly.GetCallingAssembly().GetName().Name;
            }
            catch
            {
                log.ApplicationName = "";
            }

            log.ErrorMessage = ex.Message;
            log.StackTrace = ex.StackTrace;
            if (ex.InnerException != null)
            {
                log.InnerException = ex.InnerException.ToString();
                log.InnerExceptionMessage = ex.InnerException.Message;
            }
            log.IpAddress = ""; //get the ip address

            if (System.Diagnostics.Debugger.IsAttached)
            {
                log.IsProduction = false;
            }

            try
            {
                db.Logs.InsertOnSubmit(log);
                db.SubmitChanges();
            }
            catch (Exception eex)
            {

            }
        }
    }
}

影响级别基本上是Enum

USE [database Name]
GO

/****** Object:  Table [dbo].[Log]    Script Date: 9/27/2016 11:52:32 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Log](
    [LogId] [INT] IDENTITY(1,1) NOT NULL,
    [ErrorDate] [DATETIME] NOT NULL CONSTRAINT [DF_Log_Date]  DEFAULT (GETDATE()),
    [ErrorShortDescription] [VARCHAR](1000) NULL,
    [ExceptionType] [VARCHAR](255) NULL,
    [FileName] [VARCHAR](1000) NULL,
    [LineNumber] [INT] NULL,
    [MethodName] [VARCHAR](255) NULL,
    [ClassName] [VARCHAR](150) NULL,
    [ImpactLevel] [VARCHAR](50) NOT NULL,
    [ApplicationName] [VARCHAR](255) NULL,
    [ErrorMessage] [VARCHAR](4000) NULL,
    [StackTrace] [VARCHAR](MAX) NULL,
    [InnerException] [VARCHAR](2000) NULL,
    [InnerExceptionMessage] [VARCHAR](2000) NULL,
    [IpAddress] [VARCHAR](150) NULL,
    [IsProduction] [BIT] NOT NULL CONSTRAINT [DF_Log_IsProduction]  DEFAULT ((1)),
    [LastModified] [DATETIME] NOT NULL CONSTRAINT [DF_Log_LastModified]  DEFAULT (GETDATE()),
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED 
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This table holds all the exceptions. 
ErrorData = when error happened
,[ErrorShortDescription] == short desc about the error entered by the developers
      ,[FileName] = file where error happened full path
      ,[LineNumber] = line number where code failed
      ,[MethodName] = method name where exception happened
      ,[ClassName] = class where exception happened
      ,[ImpactLevel] = high, medium, low
      ,[ApplicationName] = name of the application where error came from
      ,[ErrorMessage] = exception error messge
      ,[StackTrace] = C# stack trace
      ,[InnerException] = inner exception of strack trace
      ,[InnerExceptionMessage] = inner message
      ,[IpAddress]
      ,[IsProduction]' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Log'
GO

您可以将其用作以下内容

 public enum ImpactLevel
    {
        High = 0,
        Medium = 1,
        Low = 2,
    }

答案 7 :(得分:1)

在阅读完建议后,我最终使用了以下内容:

private void LogSystemError(string message)
{
    EventLog.WriteEntry("YourAppName", message, EventLogEntryType.Error);
}

使用System.Diagnostics可以使用EventLog类。

我避免了登录文件的选项(例如&#34; yourLogFile.txt&#34;),以避免多线程记录错误的并发问题,文件位置和访问安全性以及可能存在的问题文件变得太大了。

答案 8 :(得分:0)

我没有使用外部库log4net,而是创建了自己的简单类,高度可定制且易于使用(使用所需的名称空间编辑YOURNAMESPACEHERE)。

控制台应用程序

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

    internal static class Log
    {
        private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
        private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

        internal static void Write(LogEvent Level, string Message, bool ShowConsole = true, bool WritelogFile = true)
        {
            string Event = string.Empty;
            ConsoleColor ColorEvent = Console.ForegroundColor;

            switch (Level)
            {
                case LogEvent.Info:
                    Event = "INFO";
                    ColorEvent = ConsoleColor.White;
                    break;
                case LogEvent.Success:
                    Event = "SUCCESS";
                    ColorEvent = ConsoleColor.Green;
                    break;
                case LogEvent.Warning:
                    Event = "WARNING";
                    ColorEvent = ConsoleColor.Yellow;
                    break;
                case LogEvent.Error:
                    Event = "ERROR";
                    ColorEvent = ConsoleColor.Red;
                    break;
            }

            if (ShowConsole)
            {
                Console.ForegroundColor = ColorEvent;
                Console.WriteLine(" [{0}] => {1}", DateTime.Now.ToString("HH:mm:ss"), Message);
                Console.ResetColor();
            }

            if (WritelogFile)
            {
                if (!Directory.Exists(LogPath))
                    Directory.CreateDirectory(LogPath);

                File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
            }
        }
    }
}

没有控制台应用程序(仅日志)

using System;
using System.IO;

namespace YOURNAMESPACEHERE
{
    enum LogEvent
    {
        Info = 0,
        Success = 1,
        Warning = 2,
        Error = 3
    }

internal static class Log
{
    private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
    private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";

    internal static void Write(LogEvent Level, string Message)
    {
        string Event = string.Empty;

        switch (Level)
        {
            case LogEvent.Info:
                Event = "INFO";
                break;
            case LogEvent.Success:
                Event = "SUCCESS";
                break;
            case LogEvent.Warning:
                Event = "WARNING";
                break;
            case LogEvent.Error:
                Event = "ERROR";
                break;
        }

        if (!Directory.Exists(LogPath))
            Directory.CreateDirectory(LogPath);

        File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
    }
}

用法:

控制台应用程序

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your console, also will save a copy of this print in a .log file.
Log.Write(LogEvent.Warning, "Test message", false); // It will save the print as warning only in your .log file.
Log.Write(LogEvent.Error, "Test message", true, false); // It will print an error only in your console.

没有控制台应用程序(仅日志)

Log.Write(LogEvent.Info, "Test message"); // It will print an info in your .log file.