c# Log 日誌 以及不列印重複Log

#青鸟爱吃鱼發表於2024-04-27
c# Log 日誌  以及不列印重複Log
   public static class LogHelp
    {
        private static readonly ILog logger;

        private static readonly log4net.ILog LInfo = log4net.LogManager.GetLogger("LogInfo");
        private static readonly log4net.ILog LError = log4net.LogManager.GetLogger("LogError");

        static LogHelp()
        {
            logger = LogManager.GetLogger(typeof(LogHelp));
            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
        }

        /// <summary>
        /// 記錄Info日誌
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="ex"></param>
        public static void Info(string message)
        {
            logger.Info(message);
        }

        /// <summary>
        /// 記錄Error日誌
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="ex"></param>
        public static void Error(string message, Exception ex = null)
        {
            if (ex != null)
            {
                logger.Error(message, ex);
            }
            else
            {
                logger.Error(message);
            }
        }



        public static void Debug(object message)
        {
            logger.Debug(message);
        }

        public static void Warn(object message)
        {
            logger.Warn(message);
        }


        public static void Fatal(object message)
        {
            logger.Fatal(message);
        }

        #region 1秒內不重複記錄日誌

        private static readonly ConcurrentDictionary<string, DateTime> _logEntries = new ConcurrentDictionary<string, DateTime>();

        /// <summary>
        /// 預設 1 秒內不重複記錄Log
        /// </summary>
        /// <param name="message"></param>
        public static void NoRepeatLog(string message, Exception? ex = null, int time = 1)
        {
            try
            {
                DateTime now = DateTime.Now;
                DateTime lastLogTime;

                if (_logEntries.TryGetValue(message, out lastLogTime))
                {
                    if ((now - lastLogTime).Seconds < time)
                    {
                        // 如果同樣的訊息在過去1秒內已經被記錄過,那麼不再記錄
                        return;
                    }
                    else
                    {
                        CleanupOldEntries(time);
                    }
                }

                // 更新或新增新的時間戳
                _logEntries.AddOrUpdate(message, now, (key, oldValue) => now);

                // 實際記錄日誌的邏輯
                if (ex != null)
                {
                    logger.Error(message, ex);
                }
                else
                {
                    logger.Info(message);
                }
            }
            catch (Exception exx)
            {
                throw;
            }
        }

        // 可選:清理舊的日誌條目以避免字典變得太大
        public static void CleanupOldEntries(int time)
        {
            DateTime now = DateTime.Now;
            List<KeyValuePair<string, DateTime>> logEntriesList = _logEntries.ToList();
            for (int index = 0; index < logEntriesList.Count; index++)
            {
                var thisVal = logEntriesList[index];
                if ((now - thisVal.Value).Seconds > time) // 刪除1秒鐘之前的條目
                {
                    _logEntries.TryRemove(thisVal.Key, out _);
                }
            }
        }
        #endregion
    }
View Code

log4net.config

c# Log 日誌  以及不列印重複Log
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <!--①下面一條語句是手動新增log4net的配置-->
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net>
        <!--②手動新增log4net的配置(③在Global.asax檔案中配置)-->
        <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
        <!-- Set root logger level to ERROR and its appenders -->
        <root>
            <level value="ALL" />
            <appender-ref ref="SysAppender" />
        </root>
        <logger name="WebLogger">
            <level value="DEBUG" />
        </logger>
        <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net" additivity="false">
            <!--日誌路徑-->
            <param name="File" value="../mrcslog/mrcsdevice/" />
            <!--編碼格式-->
            <param name="Encoding" value="utf-8" />
            <!--是否是向檔案中追加日誌-->
            <param name="AppendToFile" value="true" />
            <!--允許隨時刪除日誌-->
            <!--<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />-->
            <!--固定字尾-->
            <PreserveLogFileNameExtension value="true" />
            <!--log保留天數-->
            <param name= "MaxSizeRollBackups" value= "20"/>
            <!--日誌檔名是否是固定不變的-->
            <param name="StaticLogFileName" value="false" />
            <!--日誌檔名格式為:2018-11-31.log   value="yyyy-MM-dd&quot;.log&quot;"-->
            <param name="DatePattern" value="'mrcsdevice'yyyyMMdd'.log'" />
            <!--日誌滾動模式,Composite混合模式滾動,Size按大小滾動,Date按時間滾動-->
            <param name="RollingStyle" value="Composite" />
            <!--不限制檔案數-->
            <param name="MaxSizeRollBackups" value="-1" />
            <!--每個檔案大小限制-->
            <maximumFileSize value="1GB" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
                <!--<param name="ConversionPattern" value="發生時間:%d %n內容: %n%m %n %n" />-->
            </layout>
            <!--多執行緒共用日誌-->
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
        </appender>

        <!--Info日誌--><!--
        <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net">
            <param name="File" value="Log//" /> 
            <param name="Encoding" value="utf-8" /> 
            <param name="AppendToFile" value="true" /> 
            <PreserveLogFileNameExtension value="true" /> 
            <param name= "MaxSizeRollBackups" value= "10"/> 
            <param name="StaticLogFileName" value="false" /> 
            <param name="DatePattern" value="'mrcs'yyyyMMdd'InfoLog.log'" /> 
            <param name="RollingStyle" value="Composite" />
            <param name="MaxSizeRollBackups" value="-1" />
            <maximumFileSize value="1GB" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %newline" />
            </layout>
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
        </appender>-->

        <!--Err日誌-->
        <!--<appender name="ErrAppender" type="log4net.Appender.RollingFileAppender,log4net">
            <param name="File" value="Log//" />
            <param name="Encoding" value="utf-8" />
            <param name="AppendToFile" value="true" />
            <PreserveLogFileNameExtension value="true" />
            <param name= "MaxSizeRollBackups" value= "10"/>
            <param name="StaticLogFileName" value="false" />
            <param name="DatePattern" value="'mrcs'yyyyMMdd'ERRLog.txt'" />
            <param name="RollingStyle" value="Composite" />
            <param name="MaxSizeRollBackups" value="-1" />
            <maximumFileSize value="1GB" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%newline %d [%t] %-5p %c - %m%n" />
            </layout>
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
        </appender>-->
        
        <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
            <layout type="log4net.Layout.PatternLayout,log4net">
                <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
            </layout>
        </appender>

        <!--Info日誌-->
        <logger name="LogInfo">
            <level value="INFO" />
            <appender-ref ref="InfoAppender" />
        </logger>

        <!--DEBUG日誌-->
        <logger name="LogError">
            <level value="ERR" />
            <appender-ref ref="ErrAppender" />
        </logger> 
        
    </log4net>
</configuration>
View Code

相關文章