土法煉鋼-手做寫檔案LOGbyC#

  • 9
  • 0

手做寫檔案LOGbyC#

各式各樣的LOG黨寫法…

來一段手作版本寫入TXT檔案方法

未來要改寫入LOG也很方便…..

 


  static string LogPath(string FileCatalog)
    {
        string logConfigFile = ConfigurationManager.AppSettings["LogConfigFile"];
        string loggerName = ConfigurationManager    .AppSettings["LoggerName"];
        string logPath = Path.Combine(logConfigFile, loggerName);

        if (!Directory.Exists(logPath))
        {
            Directory.CreateDirectory(logPath);
        }

        string txtPath = Path.Combine(logPath, "" + DateTime.Now.ToString("yyyyMMdd") + ".txt");

        FileInfo fileInfo = new FileInfo(txtPath);

        int threshold = 6940000;

        if (fileInfo.Exists && fileInfo.Length > threshold)
        {
            int count = 1;

            while (File.Exists(txtPath))
            {
                txtPath = Path.Combine(logPath, FileCatalog + "_" + DateTime.Now.ToString("yyyyMMdd") + "_" + count + ".txt");
                count++;
            }
        }   
        return txtPath;
    }
    
     private static void Init(string CallName, string LogMsg, string FileCatalog)
    {
        try
        {
            lock (lockMe)
            {
                string txtPath = LogPath(FileCatalog);
                using (FileStream fileStream = new FileStream(txtPath, FileMode.Append, FileAccess.Write, FileShare.None))
                {
                    using (StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8))
                    {
                        sw.WriteLine("[" + FileCatalog + "][" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "][" + Utility.GetLogonID() + "]" + CallName + ":" + LogMsg);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }