我正在将日志消息保存在我的logtext.txt文件中。我想对此文件中的日志消息进行编号,有什么解决方案可以实现这一点吗?下面是我的代码:
// Create a writer and open the file:
StreamWriter log;
if (!File.Exists(AssetXMLLogMessagesPath + ".txt"))
{
log = new StreamWriter( AssetXMLLogMessagesPath + ".txt", true);
}
else
{
log = File.AppendText(AssetXMLLogMessagesPath + ".txt");
}
// Write to the file:
log.WriteLine(" "+"<------------------------------"+" AssetImporter at "+":" +" "+ DateTime.Now.ToString("F") + "--------------------------------------->");
log.WriteLine(msg);
log.WriteLine();
// Close the stream:
log.Close();发布于 2013-09-13 23:18:30
你可以这样尝试:
public sealed class LineCounter : PatternLayoutConverter
{
private static int i= 0;
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
LineCounter.i++;
writer.Write(LineCounter.i.ToString());
}
}发布于 2013-09-13 23:50:19
您必须自己保留消息编号。所以我将创建一个负责日志记录功能的类。在这里,您添加了一个属性LogEntries,该属性在每个新的日志消息中都会增加。
例如:
public static class VerySimpleLogger
{
public static string Path{ get; set; }
public static int LogEntries { get; set; }
public static bool WithTimeStamp { get; set; }
public static void Log(string message)
{
LogEntries++;
if(WithTimeStamp)
message = string.Format("{0}. {1}:\t{2}{3}", LogEntries, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), message, Environment.NewLine);
else
message = string.Format("{0}.\t{1}{2}", LogEntries, message, Environment.NewLine);
File.AppendAllText(Path, message);
}
}用法:
VerySimpleLogger.Path = @"C:\Temp\logtext.txt";
for (int i = 1; i <= 100; i++)
{
VerySimpleLogger.Log("Log-message #" + i);
}但请注意,如果重新启动程序,LogEntries编号将再次为零。它不会count the lines in a file。因此,对于需要为一次执行创建日志文件的工具,或者对于像windows-services这样的长时间运行的应用程序来说,这可能是完美的。如果这是一个从多个用户使用的winforms应用程序,并且所有用户都应该共享相同的日志文件,那么这不是一个可行的方法。
https://stackoverflow.com/questions/18789701
复制相似问题