20190422添加換行以及時間記錄spa
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class TXTLogHelper { /// <summary> /// 對某些操做進行TXT日誌記錄 /// </summary> public static void LogBackup(string LogString) { //處理logstring,添加日期和換行 LogString = DateTime.Now.ToString() + ":" +LogString; LogString += "\r\n"; string logFolder = GetOrCreateLogFilePath(); string logFile = GetBackupLogFileName(); FileInfo file = new FileInfo(logFile); FileStream fs = file.Open(FileMode.Append, FileAccess.Write); byte[] bytes = Encoding.UTF8.GetBytes(LogString); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); fs.Dispose(); } //獲取目錄路徑,若是不存在則建立 private static string GetOrCreateLogFilePath() { string backupFolder = System.Environment.CurrentDirectory + "\\log"; if (!Directory.Exists(backupFolder)) Directory.CreateDirectory(backupFolder); return backupFolder; } private static string GetBackupLogFileName() { //爲了防止數據量過大,按照日期天天生成一個日誌文件 string logFileId = DateTime.Now.ToString("yyyy-MM-dd"); return GetOrCreateLogFilePath() + "\\" + logFileId + ".txt"; } } }
廢話不說,直接上代碼日誌
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utilities { public class TXTLogHelper { /// <summary> /// 對某些操做進行TXT日誌記錄 /// </summary> public static void LogBackup(string LogString) { string logFolder = GetOrCreateLogFilePath(); string logFile = GetBackupLogFileName(); FileInfo file = new FileInfo(logFile); FileStream fs = file.Open(FileMode.Append, FileAccess.Write); byte[] bytes = Encoding.UTF8.GetBytes(LogString); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); fs.Dispose(); } //獲取備份目錄路徑,若是不存在則建立 private static string GetOrCreateLogFilePath() { string backupFolder = System.Environment.CurrentDirectory + "\\log"; if (!Directory.Exists(backupFolder)) Directory.CreateDirectory(backupFolder); return backupFolder; } private static string GetBackupLogFileName() { //爲了防止數據量過大,按照日期天天生成一個日誌文件 string logFileId = DateTime.Now.ToString("yyyy-MM-dd"); return GetOrCreateLogFilePath() + "\\" + logFileId + ".txt"; } } }