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 }
log4net.config
<?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".log""--> <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>