appsettings.json
{"LogOnOff": true //true 开启日志;false 关闭日志
}
MyLog.cs
using System.ComponentModel;namespace Namespace
{/// <summary>/// 日志类型 枚举/// </summary>public enum LogType{[Description("调试日志")]debug,//日常调试信息//[Description("警告日志")]//warning,//有错但是程序能继续执行[Description("报错日志")]error,//有错程序抛出异常}/// <summary>/// 创建日志文件夹/// 创建日志文件/// 写入日志内容/// </summary>public class MyLog{public static bool LogOnOff = Tools.ToBool(CustomConfigManager.GetConfig("LogOnOff"), false);//日志开关,配置在config文件/// <summary>/// 写日志/// </summary>/// <param name="log">日志(必填)</param>/// <param name="ex">报错信息(选填)</param>/// <param name="LogType">日志类型(默认:debug)</param>public static void WriteLog(string log, string ex = "", LogType logType = LogType.debug){if (LogOnOff == true)//日志开关,配置在config文件{try{string path = "log/" + logType;//文件夹路径:log/info 或者 log/error 这样的...string file = path + "/" + logType + "_" + DateTime.Today.ToString("yyyyMMdd") + ".log";//文件路径+文件名+扩展名if (!Directory.Exists(path))//判断文件夹是否存在{Directory.CreateDirectory(path);//不存在,创建文件夹}if (logType == LogType.error)//报错日志(一般文件比较大可能几个G,往往打不开),所以error以分钟为单位创建文件(拆分成多个小文件){file = path + "/" + logType + "_" + DateTime.Today.ToString("yyyyMMddHHmm") + ".log";//文件路径+文件名+扩展名}using (StreamWriter sw = new StreamWriter(file, true))//创建文件或者打开已有文件{sw.WriteLine("------------------------------" + DateTime.Now + "------------------------------");if (!string.IsNullOrWhiteSpace(log)) sw.WriteLine(log);//写入日志if (!string.IsNullOrWhiteSpace(ex)) sw.WriteLine(ex);//写入报错信息(如果需要的话)sw.WriteLine("");//空一行sw.Close();}}catch { }}}}
}
调用:
MyLog.WriteLog("正在启动监听服务...");//debug日志
MyLog.WriteLog($"报错: {ex.Message}", ex.ToString(), LogType.error);//error日志