简体   繁体   English

高效写入日志文件

[英]Writing log file efficiently

In my case I've got a simple listview which contains filepths.就我而言,我有一个包含文件的简单列表视图。 When a user double clicks a filepath it does some processing and eventually opens the image.当用户双击文件路径时,它会进行一些处理并最终打开图像。 However I need to generate a log file which would output to a text file the date and name of the file executed.但是,我需要生成一个日志文件,该文件会将执行文件的日期和名称输出到文本文件中。 What I'm curious to know from you who have had experience with log files is what's an efficient way if generating a log file in this case?我很想从您那里了解日志文件的经验,如果在这种情况下生成日志文件是一种有效的方法?

  1. Each time the user clicks a listview item i open the log file and write it...possibly on a seperatr thread in the backgrouns.每次用户单击列表视图项时,我都会打开日志文件并将其写入...可能在后台的单独线程上。

  2. While the app is open, each time a user clicks a list view item I append the log data to an array in memory.当应用程序打开时,每次用户单击列表视图项时,我都会将日志数据附加到内存中的数组中。 Then when the app is closed on the closing event I write to the log file the array of logs.然后当应用程序在关闭事件上关闭时,我将日志数组写入日志文件。

What do you guys recommend or suggest and why?你们有什么推荐或建议,为什么?

In general it's recommended to use Log Frameworks.一般来说,建议使用 Log Frameworks。

But if you want to keep thing simple now, you can consider creating a log method like this:但是如果你现在想让事情变得简单,你可以考虑创建一个这样的日志方法:

The main idea is writing in file as you said, and you can do it this way for example:主要思想是像你说的那样写在文件中,你可以这样做,例如:

var path = "Path to your log file";
var message = "Message to log"
System.IO.File.AppendAllLines(path, new string[]{message});

And an example of path could be this:路径的一个例子可能是这样的:

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

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       
    }
}

You can log the exception and also custom data.您可以记录异常以及自定义数据。

LogHelper.Instance.Write(exception,"3");
LogHelper.Instance.Write("UserLoggedIn");

You may have difference log like Payment, Error, User... According to your need you need to create the instance.您可能有不同的日志,如 Payment、Error、User... 根据您的需要,您需要创建实例。

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

You can go with Nlog or Elmah logging.您可以使用Nlog或 Elmah 日志记录。 They are easy to integrate, configure and use.它们易于集成、配置和使用。

You can refer http://blog.ruchir.me/2013/06/error-logging-modules-aspnet-mvc.html blog for more detail.您可以参考http://blog.ruchir.me/2013/06/error-logging-modules-aspnet-mvc.html博客了解更多详情。

Main benefit of these tools is they are easy in configuration ie you want to maintain log in file or in database.这些工具的主要好处是它们易于配置,即您希望在文件或数据库中维护日志。 By just few setting in .config file you can switch the method.只需在 .config 文件中进行一些设置,您就可以切换方法。

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

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