Simple way to perform error logging?

后端 未结 9 1485
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 03:52

I\'ve created a small C# winforms application, as an added feature I was considering adding some form of error logging into it. Anyone have any suggestions for good ways to go a

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 04:26

    Create a class called Log.cs I am using Linq To SQl to save to the database

    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
    {
        /// 
        /// Saves the exception details to ErrorLogging db with Low Priority
        /// 
        /// The exception.
        public static void Save(this Exception ex)
        {
            Save(ex, ImpactLevel.Low, "");
        }
    
        /// 
        /// Saves the exception details to ErrorLogging db with specified ImpactLevel
        /// 
        /// The exception.
        /// The Impact level.
        public static void Save(this Exception ex, ImpactLevel impactLevel)
        {
            Save(ex, impactLevel,"");
        }
        /// 
        /// Saves the exception details to ErrorLogging db with specified ImpactLevel and user message
        /// 
        /// The exception
        /// The impact level.
        /// The error Description.
        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)
                {
    
                }
            }
        }
    }
    

    Create the following table

    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
    

    Impact Level is basically Enum

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

    You can use it as following

    try
    {
    
    
    }
    catch(Exception ex)
    {
        //this will save the exception details and mark exception as low priority
        ex.Save();
    }
    
    
    try
    {
    
    
    }
    catch(Exception ex)
    {
        //this will save the exception details with  priority you define: High, Medium,Low
        ex.Save(ImpactLevel.Medium);
    }
    
    try
    {
    
    
    }
    catch(Exception ex)
    {
        //this will save the exception details with  priority you define: High, Medium,Low
        ex.Save(ImpactLevel.Medium, "You can enter an details you want here ");
    }
    

提交回复
热议问题