C# 高效地写入日志文件

C# 高效地写入日志文件,c#,logging,C#,Logging,在我的例子中,我有一个简单的listview,其中包含filepth。当用户双击文件路径时,它会进行一些处理并最终打开图像。但是,我需要生成一个日志文件,将执行的文件的日期和名称输出到文本文件。我很想从有日志文件经验的您那里知道,在这种情况下,如果生成日志文件,什么是有效的方法 每次用户单击listview项时,我都会打开日志文件并将其写入…可能是在后台的单独线程上 当应用程序打开时,每次用户单击列表视图项时,我都会将日志数据附加到内存中的数组中。然后,当应用程序在关闭事件中关闭时,我将日志数组

在我的例子中,我有一个简单的listview,其中包含filepth。当用户双击文件路径时,它会进行一些处理并最终打开图像。但是,我需要生成一个日志文件,将执行的文件的日期和名称输出到文本文件。我很想从有日志文件经验的您那里知道,在这种情况下,如果生成日志文件,什么是有效的方法

  • 每次用户单击listview项时,我都会打开日志文件并将其写入…可能是在后台的单独线程上

  • 当应用程序打开时,每次用户单击列表视图项时,我都会将日志数据附加到内存中的数组中。然后,当应用程序在关闭事件中关闭时,我将日志数组写入日志文件


  • 你们有什么建议吗?为什么?

    通常建议使用日志框架

    <>但是如果你想保持简单的东西,你可以考虑创建这样的日志方法:

    正如你所说的,主要思想是在文件中写入,你可以这样做,例如:

    var path = "Path to your log file";
    var message = "Message to log"
    System.IO.File.AppendAllLines(path, new string[]{message});
    
    路径的一个例子是:

    var path= System.IO.Path.Combine(Application.StartupPath, "Log.txt");
    

    一般来说,建议使用日志框架

    <>但是如果你想保持简单的东西,你可以考虑创建这样的日志方法:

    正如你所说的,主要思想是在文件中写入,你可以这样做,例如:

    var path = "Path to your log file";
    var message = "Message to log"
    System.IO.File.AppendAllLines(path, new string[]{message});
    
    路径的一个例子是:

    var path= System.IO.Path.Combine(Application.StartupPath, "Log.txt");
    
    您可以使用或Elmah logging。它们易于集成、配置和使用

    你可以参考博客了解更多细节

    这些工具的主要优点是易于配置,即您希望在文件或数据库中维护日志。只需在.config文件中进行一些设置,您就可以切换该方法。

    您可以使用或Elmah日志记录。它们易于集成、配置和使用

    你可以参考博客了解更多细节

    这些工具的主要优点是易于配置,即您希望在文件或数据库中维护日志。只需在.config文件中进行一些设置,就可以切换该方法。

    LogHelper.cs

    using System;
    using System.IO;
    
    namespace Features.Helper
    {
        /// <summary>
        ///     Class to create log information
        /// </summary>
        public class LogHelper
        {
            # region "Declarations"
    
            private readonly FileInfo _logFileInfo;
            private readonly long _maxLogFileSize = 0;
            private const string _strLineBreak = "\n========================\n";
            private const string _strLineBreakCustom = "\n*********************************\n\n\n\n";
            private const string _strLineBreakEnd = "\n----------------------------------------------------------\n\n\n";
            private readonly string _strLogFilePath;
    
            # endregion
    
            public static LogHelper objLog;
    
            public static LogHelper Instance
            {
                get {
                    return objLog ?? (objLog = new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "Log\\log.txt", 0));
                }
            }      
            public static LogHelper PaymentInstance
            {
                get {
                    return objLog ??
                           (objLog =
                               new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "Log\\PaymentResponse.txt", 0));
                }
            }
    
            # region "Constructors"
    
            /// <summary>
            ///     No-argument constructor
            /// </summary>
            public LogHelper()
            {
            }
    
            /// <summary>
            ///     Log class used to write exception details or
            ///     other specific details into a text file.
            /// </summary>
            /// <param name="strLogFilePath">Full path of the log file including filename</param>
            /// <param name="maxLogFileSize">
            ///     Maximum Log Size that can be acccomodated on the disk.
            ///     (number of Bytes as Long).
            ///     Log will be deleted/cleared if size exceeds.
            ///     Pass 0 for NO LIMIT on filesize
            /// </param>
            public LogHelper(string strLogFilePath, long maxLogFileSize)
            {
                _maxLogFileSize = maxLogFileSize;
                _strLogFilePath = strLogFilePath;
                _logFileInfo = new FileInfo(strLogFilePath);
            }
    
            # endregion
    
            # region "Methods"
    
            /// <summary>
            ///     Checks the log size
            ///     -- Deletes the file if maximum size is being reached.
            /// </summary>
            /// <returns>true->if logsize has reached maximum, false-> otherwise</returns>
            private bool CheckLogSize()
            {
                try
                {
                    if (_maxLogFileSize != 0)
                    {
                        if (_logFileInfo.Length > _maxLogFileSize)
                        {
                            File.Delete(_strLogFilePath);
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    return false;
                }
                catch
                {
                    return false;
                }
            }
    
            /// <summary>
            ///     Writes exceptions to log files
            /// </summary>
            /// <param name="ex">Pass the exception ex as parameter.</param>
            /// <returns>Returns false if an exception occurs while writing to file</returns>
            public bool Write(Exception ex, string userdetails = null)
            {
                try
                {
                    CheckLogSize();
                    if (File.Exists(_strLogFilePath))
                    {
                        File.AppendAllText(_strLogFilePath, DateTime.UtcNow.ToString()
                                                            + " : Exception :"
                                                            + ex.Message + "\n"
                                                            + "Inner Exception : " + _strLineBreak
                                                            + ex.InnerException + "\n"
                                                            + "Stack Trace :" + _strLineBreak
                                                            + ex.StackTrace + "\n"
                                                            + "Date:" + _strLineBreak
                                                            + DateTime.Now.ToString() + "\n"
                                                            + " UserDetails :" + userdetails
                                                            + "Source : " + _strLineBreak
                                                            + ex.Source + _strLineBreakEnd);
                        return true;
                    }
                    File.WriteAllText(_strLogFilePath, DateTime.UtcNow.ToString()
                                                       + " : Exception :" + _strLineBreak
                                                       + ex.Message + "\n"
                                                       + "Inner Exception :" + _strLineBreak
                                                       + ex.InnerException + "\n"
                                                       + "Stack Trace :" + _strLineBreak
                                                       + ex.StackTrace + "\n"
                                                       + "Date:" + _strLineBreak
                                                       + DateTime.Now.ToString() + "\n"
                                                       + " UserDetails :" +  userdetails
                                                       + "Source :" + _strLineBreak
                                                       + ex.Source + _strLineBreakEnd);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
    
            ///// <summary>
            /////     Write custom strings apart from exceptions
            ///// </summary>
            ///// <param name="strMessage">Message to write to the file</param>
            ///// <param name="userdetails">user login details</param>
            ///// <returns>true->is successful, false-> otherwise</returns>
            public bool Write(string strMessage, string userdetails = null)
            {
                try
                {
                    if (File.Exists(_strLogFilePath))
                    {
                        File.AppendAllText(_strLogFilePath, _strLineBreak
                                                            + DateTime.UtcNow.ToString()
                                                            + "; UserDetails :" +  userdetails
                                                            + " : " + strMessage + _strLineBreakCustom);
                        return true;
                    }
                    File.WriteAllText(_strLogFilePath, _strLineBreak
                                                       + DateTime.UtcNow.ToString()
                                                       + "; UserDetails :" +  userdetails
                                                       + " : " + strMessage + _strLineBreakCustom);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            # endregion       
        }
    }
    
    您可能有不同的日志,如付款、错误、用户。。。 根据您的需要,您需要创建实例

    LogHelper.PaymentInstance.Write(exception,"3");
    LogHelper.PaymentInstance.Write("Initiate Payment Successfully");
    
    LogHelper.cs

    using System;
    using System.IO;
    
    namespace Features.Helper
    {
        /// <summary>
        ///     Class to create log information
        /// </summary>
        public class LogHelper
        {
            # region "Declarations"
    
            private readonly FileInfo _logFileInfo;
            private readonly long _maxLogFileSize = 0;
            private const string _strLineBreak = "\n========================\n";
            private const string _strLineBreakCustom = "\n*********************************\n\n\n\n";
            private const string _strLineBreakEnd = "\n----------------------------------------------------------\n\n\n";
            private readonly string _strLogFilePath;
    
            # endregion
    
            public static LogHelper objLog;
    
            public static LogHelper Instance
            {
                get {
                    return objLog ?? (objLog = new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "Log\\log.txt", 0));
                }
            }      
            public static LogHelper PaymentInstance
            {
                get {
                    return objLog ??
                           (objLog =
                               new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "Log\\PaymentResponse.txt", 0));
                }
            }
    
            # region "Constructors"
    
            /// <summary>
            ///     No-argument constructor
            /// </summary>
            public LogHelper()
            {
            }
    
            /// <summary>
            ///     Log class used to write exception details or
            ///     other specific details into a text file.
            /// </summary>
            /// <param name="strLogFilePath">Full path of the log file including filename</param>
            /// <param name="maxLogFileSize">
            ///     Maximum Log Size that can be acccomodated on the disk.
            ///     (number of Bytes as Long).
            ///     Log will be deleted/cleared if size exceeds.
            ///     Pass 0 for NO LIMIT on filesize
            /// </param>
            public LogHelper(string strLogFilePath, long maxLogFileSize)
            {
                _maxLogFileSize = maxLogFileSize;
                _strLogFilePath = strLogFilePath;
                _logFileInfo = new FileInfo(strLogFilePath);
            }
    
            # endregion
    
            # region "Methods"
    
            /// <summary>
            ///     Checks the log size
            ///     -- Deletes the file if maximum size is being reached.
            /// </summary>
            /// <returns>true->if logsize has reached maximum, false-> otherwise</returns>
            private bool CheckLogSize()
            {
                try
                {
                    if (_maxLogFileSize != 0)
                    {
                        if (_logFileInfo.Length > _maxLogFileSize)
                        {
                            File.Delete(_strLogFilePath);
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    return false;
                }
                catch
                {
                    return false;
                }
            }
    
            /// <summary>
            ///     Writes exceptions to log files
            /// </summary>
            /// <param name="ex">Pass the exception ex as parameter.</param>
            /// <returns>Returns false if an exception occurs while writing to file</returns>
            public bool Write(Exception ex, string userdetails = null)
            {
                try
                {
                    CheckLogSize();
                    if (File.Exists(_strLogFilePath))
                    {
                        File.AppendAllText(_strLogFilePath, DateTime.UtcNow.ToString()
                                                            + " : Exception :"
                                                            + ex.Message + "\n"
                                                            + "Inner Exception : " + _strLineBreak
                                                            + ex.InnerException + "\n"
                                                            + "Stack Trace :" + _strLineBreak
                                                            + ex.StackTrace + "\n"
                                                            + "Date:" + _strLineBreak
                                                            + DateTime.Now.ToString() + "\n"
                                                            + " UserDetails :" + userdetails
                                                            + "Source : " + _strLineBreak
                                                            + ex.Source + _strLineBreakEnd);
                        return true;
                    }
                    File.WriteAllText(_strLogFilePath, DateTime.UtcNow.ToString()
                                                       + " : Exception :" + _strLineBreak
                                                       + ex.Message + "\n"
                                                       + "Inner Exception :" + _strLineBreak
                                                       + ex.InnerException + "\n"
                                                       + "Stack Trace :" + _strLineBreak
                                                       + ex.StackTrace + "\n"
                                                       + "Date:" + _strLineBreak
                                                       + DateTime.Now.ToString() + "\n"
                                                       + " UserDetails :" +  userdetails
                                                       + "Source :" + _strLineBreak
                                                       + ex.Source + _strLineBreakEnd);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
    
            ///// <summary>
            /////     Write custom strings apart from exceptions
            ///// </summary>
            ///// <param name="strMessage">Message to write to the file</param>
            ///// <param name="userdetails">user login details</param>
            ///// <returns>true->is successful, false-> otherwise</returns>
            public bool Write(string strMessage, string userdetails = null)
            {
                try
                {
                    if (File.Exists(_strLogFilePath))
                    {
                        File.AppendAllText(_strLogFilePath, _strLineBreak
                                                            + DateTime.UtcNow.ToString()
                                                            + "; UserDetails :" +  userdetails
                                                            + " : " + strMessage + _strLineBreakCustom);
                        return true;
                    }
                    File.WriteAllText(_strLogFilePath, _strLineBreak
                                                       + DateTime.UtcNow.ToString()
                                                       + "; UserDetails :" +  userdetails
                                                       + " : " + strMessage + _strLineBreakCustom);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            # endregion       
        }
    }
    
    您可能有不同的日志,如付款、错误、用户。。。 根据您的需要,您需要创建实例

    LogHelper.PaymentInstance.Write(exception,"3");
    LogHelper.PaymentInstance.Write("Initiate Payment Successfully");
    

    谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢,谢谢你们。为了简单起见,现在我将使用这个解决方案。不过,本帖中的其他建议也很有用,可能是其他人的解决方案。谢谢大家提供的所有信息。为了简单起见,现在我将使用这个解决方案。然而,本线程中的其他建议也很有用,可能是其他人的解决方案。