[英]How to write log file in c#?
我將如何在 C# 中編寫日志文件?
目前我有一個帶有這個語句的計時器,它每 20 秒滴答一次:
File.WriteAllText(filePath+"log.txt", log);
對於我想要記錄的所有內容,我都這樣做:
log += "stringToBeLogged";
正如您可以假設字符串日志隨着程序運行而增長和增長。 (我什至不知道每個字符串是否有最大字符數?)
我認為必須有更好的方法來做到這一點。 我只是認為每次將某些內容添加到日志時一次又一次地寫入整個文件會很繁重。
從性能的角度來看,您的解決方案並非最佳。 每次使用+ =添加另一個日志條目時,整個字符串將被復制到內存中的另一個位置。 我建議使用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秒內添加的日志條目會發生什么。 您可能希望在應用程序退出之前將字符串刷新到文件。
創建一個類全局創建一個對象並調用它
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)
{
}
}
}
請改用File.AppendAllText :
File.AppendAllText(filePath + "log.txt", log);
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
非常方便的日志記錄工具是http://logging.apache.org/log4net/
你也可以使自己的東西變得更少(更強大)。 您可以使用http://msdn.microsoft.com/ru-ru/library/system.io.filestream(v = vs.110)。 ASPX
使用靜態類添加日志到文件
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)
{
}
}
}
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
由@randymohan發布,改為使用using語句
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);
}
}
}
有兩種簡單的方法
這是在文件中添加新字符串
using (var file = new StreamWriter(filePath + "log.txt", true))
{
file.WriteLine(log);
file.Close();
}
如果您的應用程序是多線程的,那么在某些環境中 file.appendalltext 可能會出現類似文件已在使用中的錯誤,如果您跳過它,那么您可能會丟失重要的日志。 為此,您可以將 Lock 對象技術與 file.append.. 一起使用,在這種情況下,它將等待現有進程關閉並寫入您的日志
這也可以避免您在源中添加其他庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.