Writing log file efficiently

2019-08-12 14:53发布

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?

标签: c# logging
3条回答
倾城 Initia
2楼-- · 2019-08-12 15:27

In general it's recommended to use 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");
查看更多
看我几分像从前
3楼-- · 2019-08-12 15:27

You can go with Nlog or Elmah logging. 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.

Main benefit of these tools is they are easy in configuration i.e. you want to maintain log in file or in database. By just few setting in .config file you can switch the method.

查看更多
4楼-- · 2019-08-12 15:46

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.

LogHelper.PaymentInstance.Write(exception,"3");
LogHelper.PaymentInstance.Write("Initiate Payment Successfully");
查看更多
登录 后发表回答