繁体   English   中英

高效写入日志文件

[英]Writing log file efficiently

就我而言,我有一个包含文件的简单列表视图。 当用户双击文件路径时,它会进行一些处理并最终打开图像。 但是,我需要生成一个日志文件,该文件会将执行文件的日期和名称输出到文本文件中。 我很想从您那里了解日志文件的经验,如果在这种情况下生成日志文件是一种有效的方法?

  1. 每次用户单击列表视图项时,我都会打开日志文件并将其写入...可能在后台的单独线程上。

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

日志助手

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

您可能有不同的日志,如 Payment、Error、User... 根据您的需要,您需要创建实例。

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

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

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

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

暂无
暂无

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

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