首页 > 其他分享 >自定义日志服务

自定义日志服务

时间:2023-03-09 21:57:00浏览次数:34  
标签:服务 string 自定义 filePath LogType methodName path 日志

 

    /// <summary>
    /// 日志服务
    /// </summary>
    public interface ILog
    {

        void Write(LogType logType,
            string message = "",
            [CallerFilePath] string filePath = "",
            [CallerMemberName] string methodName = "",
            [CallerLineNumber] int lineNum = 0);
    }

 

其中,LogType是日志的级别,message是日志的具体信息,可以调用的时候载入。

[CallerFilePath]特性,当某个方法A调用此方法(Write方法)时,自动将A方法所在的文件路径赋值给filePath参数,然后便可以将此路径写入到日志文件中

[CallerMemberName]特性,与CallerFilePath类似,自动将调用Write方法的方法名赋值给methodName参数

[CallerLineNumber]特性,同上,拿到调用方法在该文件中的行数

 

  public class Log : ILog
    {
        /// <summary>
        /// 向今天的Log日志中,填写Log信息
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="methodName"></param>
        /// <param name="filePath"></param>
        /// <param name="lineNum"></param>
        public void Write(LogType logType,
            string message = "",
            [CallerFilePath] string filePath = "",
            [CallerMemberName] string methodName = "",
            [CallerLineNumber] int lineNum = 0)
        {
            //  是否写日志
            if (Fields._isWriteLog)
            {
                string directoryPath = GetCurrentLogDirectoryPath();
                string path = GetCurrentLogFileFullPath();

                if (!DirectoryHelper.IsExistDirectory(directoryPath))
                {
                    DirectoryHelper.CreateDirectory(directoryPath);
                }

                switch (logType)
                {
                    case LogType.Info:
                        //  ToDo: 1. 添加往日志文件中写的方法
                        FileHelper.AppendLineToFile(path, "[ Info ] : " + DateTime.Now.ToString("T") +" " + message + ",方法名称:" + methodName);
                        break;
                    case LogType.Warning:
                        FileHelper.AppendLineToFile(path, "[ Warning ] : " + DateTime.Now.ToString("T") + " " + message + ",方法名称:" + methodName);
                        break;
                    case LogType.Error:
                        FileHelper.AppendLineToFile(path, "[ Error ] : " + DateTime.Now.ToString("T") + " " + message + "\n" +
                            "\t位置信息:" + filePath +
                            ",引发行数:" + lineNum +
                            ",方法名称:" + methodName);
                        break;
                    case LogType.Fatal:
                        FileHelper.AppendLineToFile(path, "[ Fatal ] : " + DateTime.Now.ToString("T") + " " + message + "\n" +
                            "\t位置信息:" + filePath +
                            ",引发行数:" + lineNum +
                            ",方法名称:" + methodName);
                        break;
                    default:
                        break;
                }
            }
        }

        private string GetCurrentLogDirectoryPath()
        {
            string fileFullPath = GetCurrentLogFileFullPath();

            string[] strList = fileFullPath.Split('\\');
            strList[strList.Length - 1] = "";

            string path = string.Join("\\", strList);

            return path.Trim();
        }

        /// <summary>
        /// 获取今天的Log日志文件路径及文件名称
        /// </summary>
        /// <returns></returns>
        private string GetCurrentLogFileFullPath()
        {
            return Fields._logDataDirectory + "\\" + DateTime.Now.ToString("D") + "\\" + DateTime.Now.ToString("D") + ".txt";
        }
    }
 

 

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogType
    {
        Info = 1,
        Warning = 2,
        Error = 3,
        Fatal = 4,
    }

 

定义一个日志的实现类,该类提供一个写日志的方法。然后在需要打日志的地方调用该方法,例如:

        public static void CreateFile(string filePath)
        {
            try
            {
                FileLower.CreateFile(filePath);
            }
            catch (FileException fe)
            {
                _log.Write(LogType.Error, fe.Message);
            }
            catch (Exception ex)
            {
                _log.Write(LogType.Error, ex.Message);
            }
        }

 

如果创建目标文件失败的时候,可以调用打日志的方法,将失败的信息记录下来。

注:如果在创建文件的方法中打日志,并且日志写的时候发现文件不存在,然后又需要创建日志文件,此时会进入死循环,然后抛出异常:StackOverFlow,爆栈。这个时候需要处理一下,防止进入死循环。

 

另外,

1.可以再记录一下,日志总共写了多少行,比如1W行,重新生成一个日志文件(日志文件名以当前时间为名称作为区分)。

2.也可以将记录的天数做一个判定,比如只保存一个月内的记录,到时间后就将其删除掉。

标签:服务,string,自定义,filePath,LogType,methodName,path,日志
From: https://www.cnblogs.com/OctopusKing/p/17201609.html

相关文章

  • [ssh] 本地访问远程服务器上的ui页面
    [ssh]本地访问远程服务器上的ui页面问题:在我们使用某些系统(如Spark)时,系统本身会为我们提供一个ui界面,这个ui界面会默认开启在一个本地端口上(如localhost:8080)。通过这个u......
  • MongoDb服务搭建
    参考官网教程:https://www.mongodb.com/docs/v4.4/tutorial/install-mongodb-on-red-hat/1、配置yum仓库,安装[mongodb-org]name=MongoDBRepositorybaseur......
  • Redis服务搭建
    一、服务搭建1、安装gcc套装yuminstallcppyuminstallbinutilsyuminstallglibcyuminstallglibc-kernheadersyuminstallglibc-common......
  • uni-app:发布为h5站点时服务端的api配置
    一,开发环境中对接口跨域的配置manifest.json中添加"h5":{"devServer":{"https":false,"disableHostCheck":true,......
  • Shiro自定义Realm实现认证
       7.4.2 自定义Realm      ......
  • Linux高并发服务器之Linux多线程开发
    本文源自C++高薪面试项目的学习笔记,主要记录Liunx多线程的学习,主要知识点是线程概述等基础概念以外,还有线程相关Liunx系统函数以及对应练手代码,除此之外还有线程同步问题的......
  • 斯坦福 UE4 C++ ActionRoguelike游戏实例教程 02.AI自定义任务和观察器中断
    斯坦福课程UE4C++ActionRoguelike游戏实例教程0.绪论概述本文章对应课程第十一章42节。这篇文章会进一步地为AI添加新功能,创建自定义任务,允许AI发射子弹,并且讲解观......
  • 用VPS云服务器部署ChatGPT
    用VPS云服务器部署ChatGPT前言chatgpt做为近期爆火的人工智能服务,其账号和api接口的价格水涨船高。这里给出一个粗略的api部署方法,仅供参考。文章结构:注册ChatGPT......
  • 问题记录:jss文件服务器定时任务下载失败
    jss文件服务器定时任务下载失败报错信息:客户端http连接池获取连接超时问题背景:每5min跑一次定时任务,从文件服务器下载文件更新内存,但是更新内存前会拿文件更新时间进行......
  • SQL Server 自定义DateTime格式化显示内容
    SQLServer的Convert函数没有想要的格式类型,需要自定义显示格式。CASTandCONVERT(Transact-SQL)Thesefunctionsconvertanexpressionofonedatatypetoanothe......