如何在c#中编写日志文件?
目前我有一个带有此语句的计时器,每20秒计时一次:
File.WriteAllText(filePath+"log.txt", log);
对于我想要记录的所有内容,我这样做:
log += "stringToBeLogged";
正如您可以假设字符串日志随着程序的运行而增长和增长。 (我甚至不知道每个字符串是否有最大字符数?)
我认为必须有更好的方法来做到这一点。我只是觉得每次将某些内容添加到日志中时,反复写入整个文件会很重。
答案 0 :(得分:41)
从性能的角度来看,您的解决方案并非最佳。每次使用+ =添加另一个日志条目时,整个字符串将被复制到内存中的另一个位置。我建议改用StringBuilder:
StringBuilder sb = new StringBuilder();
...
sb.Append("log something");
...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();
顺便说一句,你的计时器事件可能在另一个线程上执行。因此,您可能希望在访问sb
对象时使用互斥锁。
要考虑的另一件事是在执行的最后20秒内添加的日志条目会发生什么。您可能希望在应用程序退出之前将字符串刷新到文件中。
答案 1 :(得分:32)
创建一个类全局创建一个对象并调用此
using System.IO;
using System.Reflection;
public class LogWriter
{
private string m_exePath = string.Empty;
public LogWriter(string logMessage)
{
LogWrite(logMessage);
}
public void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
{
Log(logMessage, w);
}
}
catch (Exception ex)
{
}
}
public void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
答案 2 :(得分:13)
改为使用File.AppendAllText:
File.AppendAllText(filePath + "log.txt", log);
答案 3 :(得分:11)
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
参考链接: blogspot.in
答案 4 :(得分:6)
非常方便的记录工具是http://logging.apache.org/log4net/
你也可以让自己的东西更少(更强大)。您可以使用http://msdn.microsoft.com/ru-ru/library/system.io.filestream (v = vs.110). Aspx
答案 5 :(得分:4)
使用静态类
添加日志到文件 public static class LogWriter
{
private static string m_exePath = string.Empty;
public static void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!File.Exists(m_exePath + "\\" + "log.txt"))
File.Create(m_exePath + "\\" + "log.txt");
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
AppendLog(logMessage, w);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void AppendLog(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
答案 6 :(得分:2)
if(!File.Exists(filename)) //No File? Create
{
fs = File.Create(filename);
fs.Close();
}
if(File.ReadAllBytes().Length >= 100*1024*1024) // (100mB) File to big? Create new
{
string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
if(filename.contains("-")) //Check if older log contained -x
{
int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
lognumber++; //Increment lognumber by 1
filename = filenamebase + "-" + lognumber + ".log"; //Override filename
}
else
{
filename = filenamebase + "-1.log"; //Override filename
}
fs = File.Create(filename);
fs.Close();
}
参考链接:
http://www.codeproject.com/Questions/163337/How-to-write-in-log-Files-in-C
答案 7 :(得分:2)
由@randymohan发布,使用语句代替
public static void WriteLog(string strLog)
{
string logFilePath = @"C:\Logs\Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
FileInfo logFileInfo = new FileInfo(logFilePath);
DirectoryInfo logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append))
{
using (StreamWriter log = new StreamWriter(fileStream))
{
log.WriteLine(strLog);
}
}
}
答案 8 :(得分:1)
有两种简单方法
答案 9 :(得分:0)
这是在文件中添加新字符串
using (var file = new StreamWriter(filePath + "log.txt", true))
{
file.WriteLine(log);
file.Close();
}