日志帮助类

工作中经常在调试代码的时候采用日志的形式去记录异常情况,一般都是采公司的一个日志帮助类,没有自己写过相关代码,今天自己写了一个日志帮助类,其中可以记录相关文本内容,‘

如果只输入日志内容,测文本按照日期的格式,把日志写入程序所在的根目录。同时可以设置文件的路径,文件的名称,和文件是增加或者保持最新的一个。全部代码如下:

定义日志接口:

interface ILogHelp
    {
        bool WriteLog(string msg);
        bool WriteLog(string msg, string path);
        bool WriteLog(string msg, string path, string fileName);
        bool WriteLog(string msg, string path, string fileName, bool isdelete);
    }

接口隐式实现代码:

public  class LogHelp:ILogHelp
    {
        public bool WriteLog(string msg)
        {
            var currenPath = System.AppDomain.CurrentDomain.BaseDirectory + "/Logs";
            var fileName = System.DateTime.Now.ToString("yyyy-MM-dd hhmmss") + ".txt";
            var filepath = Path.Combine(currenPath, fileName);
            if (!Directory.Exists(currenPath))
                Directory.CreateDirectory(currenPath);
               File.AppendAllText(filepath,msg);
            return true;
        }

        public bool WriteLog(string msg, string path)
        {
            var currenPath= path + @"/Logs";
            var fileName = System.DateTime.Now.ToString("yyyy-MM-dd hhmmss") + ".txt";
            var filepath = Path.Combine(currenPath, fileName);
            if (!Directory.Exists(currenPath))
                Directory.CreateDirectory(currenPath);
            File.AppendAllText(filepath, msg);
            return true;

        }

        public bool WriteLog(string msg, string path, string fileName)
        {
            var currenPath = path + "/Logs";
            var filepath = Path.Combine(currenPath, fileName) + ".txt";
            if (!Directory.Exists(currenPath))
                Directory.CreateDirectory(currenPath);
            File.AppendAllText(filepath, msg);
            return true;
        }

        public bool WriteLog(string msg, string path, string fileName, bool isdelete)
        {
            var currenPath = path + "/Logs";
            var filepath = Path.Combine(currenPath, fileName) + ".txt";
            if (!Directory.Exists(currenPath))
            {
                Directory.CreateDirectory(currenPath);
            }
            if(isdelete&&File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            else if (!Directory.Exists(currenPath))
                Directory.CreateDirectory(currenPath);
            File.AppendAllText(filepath, msg);
            return true;

        }
    }
View Code
原文地址:https://www.cnblogs.com/yanwuming/p/8679212.html