我正在c#,。Net 3.5中开发一个Windows窗体。我使用log4net显示不同的日志消息。 我的日志消息如下:
ERROR 15.11.2016 12:47:24 - 计算机:SUPER,用户:XYZ,模块:ServiceA,方法:loadSettings,[ERROR1001] Connectionlost
ERROR 15.11.2016 12:47:34 - 计算机:SUPER,用户:XYZ,模块:ServiceA,方法:loadSettings,[ERROR1001] Connectionlost
ERROR 15.11.2016 12:47:44 - 计算机:SUPER,用户:XYZ,模块:ServiceA,方法: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;
}
}
答案 0 :(得分:0)
您可以阅读日志的所有行并搜索它们是否包含日志消息并检查其时间戳以匹配您的条件,但是没有看到您附加时间戳的部分或日志增长的大小这是排序疯狂猜测..
无论如何,做这样的事情应该相当简单:
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
}
答案 1 :(得分:0)
您可以执行以下操作:
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;
}
}