簡體   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