iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 8
0
Modern Web

MVC概略與分享系列 第 7

[鐵人賽D8] Nlog設定

  • 分享至 

  • xImage
  •  

小弟的MVC專案是使用Nlog來記錄錯誤,是個在nuget上相當好用的工具

安裝Nlog
管理nuget套件
https://ithelp.ithome.com.tw/upload/images/20181023/20111766RNj67eDkB7.png

搜尋Nlog並且安裝
https://ithelp.ithome.com.tw/upload/images/20181023/20111766bg2IFsYoVE.png

專案的參考會加入nlog,並且會有nlog的config檔
https://ithelp.ithome.com.tw/upload/images/20181023/20111766Z3FstXZYch.png

到目前為止就安裝成功

範例
寫了一個範例,logType區分寫入log類型,主要分為五大類型的log
-Trace
-Info
-Warn
-Debug
-Error

    public class BaseLog
    {
        protected static readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 紀錄Log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="logType"></param>
        public void SetLogger(string message, LogType logType)
        {
            switch (logType)
            {
                case LogType.Trace:
                    logger.Trace(message);
                    break;
                case LogType.Debug:
                    logger.Debug(message);
                    break;
                case LogType.Info:
                    logger.Info(message);
                    break;
                case LogType.Warn:
                    logger.Warn(message);
                    break;
                case LogType.Error:
                    logger.Error(message);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 撰寫追蹤LOG為主
        /// </summary>
        /// <param name="objLogInfo"></param>
        /// <param name="ex"></param>
        public void WriteTraceLog(string strMessage)
        {
            SetLogger(strMessage, LogType.Trace);
        }

        /// <summary>
        /// 撰寫SQLLOG為主
        /// </summary>
        /// <param name="objLogInfo"></param>
        /// <param name="ex"></param>
        public void WriteSqlLog(LogInfoModel objLogInfo)
        {
            objLogInfo.Type = LogType.Info;
            SetLogger(FormatLog(objLogInfo), LogType.Debug);
        }

        /// <summary>
        /// 撰寫錯誤LOG為主
        /// </summary>
        /// <param name="objLogInfo"></param>
        /// <param name="ex"></param>
        public void WriteErrorLog(LogInfoModel objLogInfo, string ex)
        {
            objLogInfo.Type = LogType.Error;
            objLogInfo.Exception = ex;
            SetLogger(FormatLog(objLogInfo), LogType.Error);
        }

        /// <summary>
        /// 撰寫登入LOG為主
        /// </summary>
        /// <param name="objLogInfo"></param>
        /// <param name="ex"></param>
        public void WriteLoginTime(EmpUserModel loginUser, string ip)
        {
            StringBuilder strLog = new StringBuilder();
            strLog.AppendLine("[Login]" + loginUser.USER_ID);
            strLog.AppendLine("[IP]" + ip);

            SetLogger(strLog.ToString(), LogType.Info);
        }

        /// <summary>
        /// 撰寫後台管理者登入LOG
        /// </summary>
        /// <param name="objLogInfo"></param>
        /// <param name="ex"></param>
        public void WriteAdminLoginInfo(string userID, string ip)
        {
            StringBuilder strLog = new StringBuilder();
            strLog.AppendLine("[Login]" + userID);
            strLog.AppendLine("[IP]" + ip);

            SetLogger(strLog.ToString(), LogType.Warn);
        }

        /// <summary>
        /// 格式化LOG訊息
        /// </summary>
        /// <param name="objLogInfo">LOG訊息物件</param>
        /// <returns>格式化後的LOG訊息</returns>
        public string FormatLog(LogInfoModel objLogInfo)
        {
            StringBuilder logInfo = new StringBuilder();

            //依造domain object定義順序依序寫出裡面內容
            foreach (System.Reflection.PropertyInfo objItem in objLogInfo.GetType().GetProperties())
            {
                if (objItem.GetValue(objLogInfo, null) != null)
                {
                    logInfo.AppendLine("[" + objItem.Name + "]");
                    logInfo.AppendLine(objItem.GetValue(objLogInfo, null).ToString());
                    logInfo.AppendLine("");
                }
            }

            return logInfo.ToString();
        }
    }

nlog如下設定

    <target xsi:type="File" name="ErrorLog" fileName="D://Logs/TEST/${shortdate}/ErrorLog.txt"
             layout="${newline}[${uppercase:${level}}]${longdate}${newline}[${uppercase:${level}}]${message}" 
             archiveFileName="D://Logs/TEST/${shortdate}/ErrorLog_{###}.txt"
             archiveAboveSize="5242880" maxArchiveFiles="100"/>
    <target xsi:type="File" name="SqlLog" fileName="D://Logs/MOST_WST/${shortdate}/Sql.txt"
             layout="[${uppercase:${level}}]${longdate}${newline}[${uppercase:${level}}]${message}"
             archiveFileName="D://Logs/TEST/${shortdate}/Sql_{###}.txt"
             archiveAboveSize="5242880" maxArchiveFiles="100"/>
    <target xsi:type="File" name="InfoLog" fileName="D://Logs/TEST/${shortdate}/LoginInfoLog.txt"
             layout="${newline}[${uppercase:${level}}]${longdate}${newline}[${uppercase:${level}}]${message}" />
    <target xsi:type="File" name="WarnLog" fileName="D://Logs/TEST/${shortdate}/AdminLoginLog.txt"
             layout="[${uppercase:${level}}]${longdate}${newline}[${uppercase:${level}}]${message}" />
    <target xsi:type="File" name="ExecLog" fileName="D://Logs/TEST/${shortdate}/ExecProgramLog.txt"
             layout="${newline}[${uppercase:${level}}]${longdate}${newline}[${uppercase:${level}}]${message}" />
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
    <logger name="*" level="Error" writeTo="ErrorLog" />
    <logger name="*" level="Warn" writeTo="WarnLog" />
    <logger name="*" level="Info" writeTo="InfoLog" />
    <logger name="*" level="Debug" writeTo="SqlLog" />
    <logger name="*" level="Trace" writeTo="ExecLog" />
  </rules>

最後會產生文字檔如下,並以日期去區分
https://ithelp.ithome.com.tw/upload/images/20181023/20111766AA0x7GaL9R.png


上一篇
[鐵人賽D7] KendoUI
下一篇
[鐵人賽D9] Web.config設定
系列文
MVC概略與分享9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言