如何忽略已经存在的特定日志消息
本文关键字:日志 消息 存在 何忽略 | 更新日期: 2023-09-27 18:18:04
我正在用c#开发一个windows窗体。Net 3.5。我使用log4net来显示不同的日志消息。我的日志信息看起来像:
ERROR 15.11.2016 12:47:24 - Computer: SUPER, User:XYZ, Module: ServiceA, Method: loadSettings, [ERROR1001] Connectionlost
ERROR 15.11.2016 12:47:34 - Computer: SUPER, User:XYZ, Module: ServiceA, Method: loadSettings, [ERROR1001] Connectionlost
ERROR 15.11.2016 12:47:44 - Computer: SUPER, User:XYZ, Module: ServiceA, Method: loadSettings, [ERROR1001] Connectionlost
是否有办法检查日志信息是否已经存在?如果出现上述消息,我想显示一次。
下面是我的代码:private static void Log(string message, string type, string module)
{
try
{
sLogMessage = string.Format("Computer: {0}, User: {1}, Module: {2}, Method: {3}, [{4}] {5}{6}",
System.Environment.MachineName, System.Environment.UserName,
module, new StackTrace().GetFrame(2).GetMethod().Name,
type, message, Environment.NewLine);
}
catch (Exception)
{
}
switch (type)
{
case "DEBUG": logger.Debug(sLogMessage);
break;
case "INFO":
try
{
logger.Info(sLogMessage);
}
catch (Exception)
{
}
break;
case "WARNING": logger.Warn(sLogMessage);
break;
//here displays my error message and i want to check if it already exixts
case "ERROR": logger.Error(sLogMessage);
break;
}
}
您可以读取日志的所有行并搜索它们是否包含日志消息并检查它们的时间戳以匹配您的条件,但是没有看到您附加时间戳的部分或日志增长的大小这是一种野蛮的猜测…
无论如何,这样做应该是相当简单的:
string sLogMessage = "your Log message";
DateTime yourTimeStamp = DateTime.Now;
if (!File.ReadAllLines("PathToLogFile").Any(l => l.Contains(sLogMessage) &&
(DateTime.Parse(l.Substring("extract the timestamp from the line")) - yourTimeStamp).TotalDays < 1))
{
//Add it to the log
}
你可以这样做:
private class LogMessage
{
string module { get; set; }
string message { get; set; }
DateTime LoggedOn { get;set;}
}
private List<LogMessage> messages = new List<LogMessage>();
private static void Log(string message, string type, string module)
{
/* remove any messages older than X time */
if(messages.Where(x => x.module == module && x.message == message).Any())
{
// You can add more properties to the where for comparison
// Already exist so return
return;
}
messages.Add(new LogMessage() { module = module, message = message, LoggedOn = DateTime.Now});
try
{
sLogMessage = string.Format("Computer: {0}, User: {1}, Module: {2}, Method: {3}, [{4}] {5}{6}",
System.Environment.MachineName, System.Environment.UserName,
module, new StackTrace().GetFrame(2).GetMethod().Name,
type, message, Environment.NewLine);
}
catch (Exception)
{
}
switch (type)
{
case "DEBUG": logger.Debug(sLogMessage);
break;
case "INFO":
try
{
logger.Info(sLogMessage);
}
catch (Exception)
{
}
break;
case "WARNING": logger.Warn(sLogMessage);
break;
//here displays my error message and i want to check if it already exixts
case "ERROR": logger.Error(sLogMessage);
break;
}
}