20181015记录一个简单的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";
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/lovejunjuan/p/9789324.html