C# 写日志帮助类
2022/2/22 17:26:18
本文主要是介绍C# 写日志帮助类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/*----------------------------------------------------------------- * 作 者(Author): Dennis * 日 期(Create Date): 2021/9/3 16:11:39 * 公 司(Copyright): www.dennisdong.top * 文件名(File Name): LogFileHelper * ---------------------------------------------------------------- * 描 述(Description): *----------------------------------------------------------------*/ using System; using System.IO; namespace Anta.Common.Helpers { /// <summary> /// 自定义文件写入 /// </summary> public class LogFileHelper { private static readonly object LogLock = new object(); /// <summary> /// 日志默认存放路径 /// </summary> private static readonly string LogPath = $@"{AppDomain.CurrentDomain.BaseDirectory}\LogFiles\"; #region WriteLog /// <summary> /// 只记录信息 /// </summary> /// <param name="msg">内容</param> public static void WriteLog(string msg) { WriteLog(null, null, msg); } /// <summary> /// 路径加信息 /// </summary> /// <param name="filePath">相对路径</param> /// <param name="msg">内容</param> public static void WriteLog(string filePath, string msg) { WriteLog(filePath, null, msg); } /// <summary> /// 写入日志 /// </summary> /// <param name="filePath">相对路径</param> /// <param name="fileName">文件名</param> /// <param name="msg">内容</param> public static void WriteLog(string filePath, string fileName, string msg) { lock (LogLock) { try { if (string.IsNullOrEmpty(filePath)) { filePath = "LogDefault"; } filePath = LogPath + filePath; if (!Directory.Exists(filePath))//判断是否有该文件 Directory.CreateDirectory(filePath); if (string.IsNullOrEmpty(fileName)) { fileName = DateTime.Now.ToString("yyyyMMdd"); } var logFileName = filePath + "/" + fileName + ".log";//生成日志文件 var fs = !File.Exists(logFileName) ? new FileStream(logFileName, FileMode.Create) : new FileStream(logFileName, FileMode.Append); var sw = new StreamWriter(fs); sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} \n{msg}"); sw.Flush(); sw.Close(); } catch (Exception e) { var path = LogPath + "/LogError"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); var logFileName = path + "/" + DateTime.Now.ToString("yyyyMMdd") + ".log"; var fs = !File.Exists(logFileName) ? new FileStream(logFileName, FileMode.Create) : new FileStream(logFileName, FileMode.Append); var sw = new StreamWriter(fs); sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} \n{msg} \n {e.Message}"); sw.Flush(); sw.Close(); } } } #endregion } }
这篇关于C# 写日志帮助类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具