有效地编写日志文件

时间:2015-09-11 05:02:25

标签: c# logging

在我的情况下,我有一个包含filepths的简单列表视图。当用户双击文件路径时,它会进行一些处理并最终打开图像。但是,我需要生成一个日志文件,该文件将向文本文件输出所执行文件的日期和名称。我很想知道你有过日志文件经验的人,如果在这种情况下生成日志文件,这是一种有效的方法吗?

  1. 每次用户点击listview项目时,我都会打开日志文件并将其写入...可能在背景中的一个单独的线程上。

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

  3. 你们有什么建议或建议?为什么?

2 个答案:

答案 0 :(得分:2)

一般情况下,建议使用Log Frameworks。

但是如果你想现在保持简单,你可以考虑创建一个这样的日志方法:

主要的想法是按照你说的写入文件,你可以这样做,例如:

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");

答案 1 :(得分:1)

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.Instance.Write(exception,"3");
LogHelper.Instance.Write("UserLoggedIn");

您可能有不同的日志,如付款,错误,用户... 根据您的需要,您需要创建实例。

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