【问题标题】:How to write log file in c#?如何在 C# 中写入日志文件?
【发布时间】:2013-12-09 16:53:04
【问题描述】:

如何在 C# 中编写日志文件?

目前我有一个带有此语句的计时器,每 20 秒滴答一次:

File.WriteAllText(filePath+"log.txt", log);

对于我想要记录的所有内容,我都会这样做:

log += "stringToBeLogged";

您可以假设字符串日志随着程序的运行而不断增长。 (我什至不知道每个字符串是否有最大字符数?)

我认为必须有更好的方法来做到这一点。我只是认为每次将某些内容添加到日志时一次又一次地写入整个文件会很繁重。

【问题讨论】:

  • 我建议发现类似 log4net 的东西

标签: c# logging


【解决方案1】:

从性能的角度来看,您的解决方案不是最佳的。每次使用 += 添加另一个日志条目时,整个字符串都会复制到内存中的另一个位置。我建议改用 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 秒内添加的日志条目会发生什么情况。您可能希望在应用退出之前将字符串刷新到文件中。

【讨论】:

  • Herehere 是另一个解决方案。希望有所帮助。
【解决方案2】:

创建一个类全局创建一个对象并调用它

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)
        {
        }
    }
}

【讨论】:

  • 这是一个出色的解决方案,运行良好!
  • 不错,但是如果使用静态类和方法,它会更干净。
【解决方案3】:

改用File.AppendAllText

File.AppendAllText(filePath + "log.txt", log);

【讨论】:

  • +1 只是一个小节点:确保您的 filePath 以斜杠结尾或添加它。您还应该添加一个新行,例如 File.AppendAllText(filePath + "\" + "log.txt", log + Environment.NewLine);
  • 鉴于他在问题中指定了log += "stringToBeLogged";,由于逐渐添加相同的信息,这将无法正常工作。应该类似于File.AppendAllText(filePath + "log.txt", 'stringToBeLogged');
  • @AlexPandrea 对,所以如果他每次都记录相同的logFile.WriteAllText 会更适合它,即使这有点多。此解决方案建议每次仅记录特定信息(附加),而不是写入完整的 log 变量。
  • @nixda,最好使用Path.DirectorySeparatorChar 而不是硬编码的\ char
【解决方案4】:
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

【讨论】:

  • 最好将StreamWriterFileStream 与嵌套的using() 块一起使用。
【解决方案5】:

使用静态类将日志添加到文件

 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)
                {
                }
            }
        }

【讨论】:

  • 这个类需要一点点修改: m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!File.Exists(m_exePath + "\\" + "log.txt")){ string s = ""; s = DateTime.Now.ToString("h:mm:ss tt"); FileStream fs = File.Create(m_exePath + "\\" + "log.txt"); Byte[] info = new UTF8Encoding(true).GetBytes("文件创建:"+s+"\r\n"); fs.Write(info, 0, info.Length);fs.Close(); }否则在第一个程序启动时你会遇到异常
  • 或创建后立即关闭文件
【解决方案6】:

@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);
        }
    }
}

【讨论】:

  • 在做new FileStream之前不要创建文件。它将创建文件。
  • 删除文件存在检查
【解决方案7】:

非常方便的日志记录工具是http://logging.apache.org/log4net/

您还可以让自己的某些东西变得不那么(更)强大。你可以使用http://msdn.microsoft.com/ru-ru/library/system.io.filestream (v = vs.110). Aspx

【讨论】:

【解决方案8】:
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

【讨论】:

    【解决方案9】:

    这是在文件中添加新字符串

    using (var file = new StreamWriter(filePath + "log.txt", true))
            {
                file.WriteLine(log);
                file.Close();
            }
    

    【讨论】:

      【解决方案10】:

      有两种简单的方法

      【讨论】:

        【解决方案11】:

        如果您的应用程序是多线程的,那么在某些环境中 file.appendalltext 可能会出现类似文件已在使用中的错误,如果您跳过该错误,那么您可能会丢失重要的日志。 为此,您可以使用 使用 file.append 锁定对象技术。在这种情况下,它将等待现有进程关闭并写入您的日志

        这也可以让您免于在源代码中添加其他库

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-01
          • 2016-08-02
          • 1970-01-01
          • 2022-12-29
          • 1970-01-01
          • 2013-11-26
          • 2014-10-18
          相关资源
          最近更新 更多