首页 > 其他分享 >用log4net写入不同路径的日志文件

用log4net写入不同路径的日志文件

时间:2024-04-17 10:47:17浏览次数:25  
标签:log4net Loggers string 写入 jobName patternLayout key 日志 appender

 

 

用log4net写入不同路径的日志文件

    /// <summary>
    /// 根据_jobName路径 写入不同日志
    /// </summary>
    public class NLogger
    {
        private static Dictionary<string, ILog> Loggers = new Dictionary<string, ILog>();
        private string jobName = string.Empty; 
        private object locker = new object();
        private static readonly object configLocker = new object();
        private static bool isConfigured = false;
        public NLogger(string _jobName)
        {
            LoadLog4netConfig();
            jobName = _jobName;
        }



        private void LoadLog4netConfig()
        {
            if (!isConfigured)
            {
                lock (configLocker)
                {
                    // 再次检查配置是否已经加载,以避免在锁获取期间发生更改
                    if (!isConfigured)
                    {
                        // 初始化日志配置
                        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
                        PatternLayout patternLayout = new PatternLayout();
                        patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
                        patternLayout.ActivateOptions();

                        hierarchy.Root.Level = log4net.Core.Level.All;
                        hierarchy.Configured = true;

                        // 标记配置为已加载,以防止未来的重复加载
                        isConfigured = true;
                    }
                }
            }
        }

        public void Info(string message)
        {
            //var _key = $"{jobName}_{DateTime.Now.ToString("yyyyMMdd")}_{LogLevel.Info.GetHashCode()}";
            var _key = $"{jobName}_{LogLevel.Info.GetHashCode()}";
            lock (locker)
            {
                if (!Loggers.ContainsKey(_key))
                {
                    CreateLogger(jobName, LogLevel.Info);
                }
                Loggers[_key].Info(message);
            }
        }
        public void Debug(string message)
        {
            //var _key = $"{jobName}_{DateTime.Now.ToString("yyyyMMdd")}_{LogLevel.Debug.GetHashCode()}";
            string _key = $"{jobName}_{LogLevel.Debug.GetHashCode()}";
            lock (locker)
            {
                if (!Loggers.ContainsKey(_key))
                {
                    CreateLogger(jobName, LogLevel.Debug);
                }
                Loggers[_key].Debug(message);
            }
        }
        public void Error(string message)
        {
            //var _key = $"{jobName}_{DateTime.Now.ToString("yyyyMMdd")}_{LogLevel.Error.GetHashCode()}";
            string _key = $"{jobName}_{LogLevel.Error.GetHashCode()}";
            lock (locker)
            {
                if (!Loggers.ContainsKey(_key))
                {
                    CreateLogger(jobName, LogLevel.Error);
                }
                Loggers[_key].Error(message);
            }
        }


        //private void CreateLogger(string jobName, LogLevel level)
        //{
        //    Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

        //    PatternLayout patternLayout = new PatternLayout();
        //    patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
        //    patternLayout.ActivateOptions();

        //    // 从 App.config 读取 logs 路径  
        //    string logDirectory = ConfigurationManager.AppSettings["LogDirectory"];
        //    if (string.IsNullOrEmpty(logDirectory))
        //    {
        //        logDirectory = "logs";
        //    }

        //    RollingFileAppender appender = new RollingFileAppender();
        //    appender.Layout = patternLayout;
        //    // 使用读取到的路径来设置 appender 的 File 属性  
        //    appender.File = Path.Combine(logDirectory, jobName, $"{level}_{DateTime.Now.ToString("yyyyMMdd")}.txt");
        //    //appender.File = $"logs/{jobName}/{level}_{DateTime.Now.ToString("yyyyMMdd")}.txt";
        //    appender.AppendToFile = true;
        //    appender.RollingStyle = RollingFileAppender.RollingMode.Date;
        //    appender.MaxSizeRollBackups = 100;
        //    appender.MaximumFileSize = "100MB";
        //    appender.StaticLogFileName = true;
        //    appender.ActivateOptions();

        //    var _key = $"{jobName}_{level.GetHashCode()}";
        //    Logger logger = (Logger)hierarchy.GetLogger(_key);
        //    logger.AddAppender(appender);
        //    logger.Level = hierarchy.Root.Level;
        //    logger.Repository.Configured = true;
        //    Loggers.Add(_key, LogManager.GetLogger(_key));
        //}
        private void CreateLogger(string jobName, LogLevel level)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            // 从 App.config 读取 logs 路径  
            string logDirectory = ConfigurationManager.AppSettings["LogDirectory"];
            if (string.IsNullOrEmpty(logDirectory))
            {
                logDirectory = "logs";
            }

            RollingFileAppender appender = new RollingFileAppender();
            appender.Layout = patternLayout;
            // 使用读取到的路径来设置 appender 的 File 属性,但不包含日期部分  
            appender.File = Path.Combine(logDirectory, jobName, $"{level}");
            appender.AppendToFile = true;
            // 正确设置 RollingStyle 属性  
            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            appender.MaxSizeRollBackups = 100;
            appender.MaximumFileSize = "300MB";
            appender.StaticLogFileName = false; // 允许文件名根据 DatePattern 滚动  
            appender.DatePattern = $"'_'yyyyMMdd'.txt'"; // 注意这里的引号,它们将作为文件名的后缀   //< datePattern value = "'Info_'yyyyMMdd'.txt'" />
            appender.ActivateOptions(); // 激活选项以应用配置

            //RollingFileAppender appender = new RollingFileAppender();
            //appender.Layout = patternLayout;
            //// 使用读取到的路径来设置 appender 的 File 属性  
            //appender.File = Path.Combine(logDirectory, jobName, $"{level}_{DateTime.Now.ToString("yyyyMMdd")}.txt");
            ////appender.File = $"logs/{jobName}/{level}_{DateTime.Now.ToString("yyyyMMdd")}.txt";
            //appender.AppendToFile = true;
            //appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            //appender.MaxSizeRollBackups = 100;
            //appender.MaximumFileSize = "300MB";
            //appender.StaticLogFileName = false;
            //appender.DatePattern = "yyyyMMdd"; 
            //appender.ActivateOptions();



            ////创建实例,第一个参数是一个ILoggerRepository对象,它是log4net中日志记录器存储库的实例,必须有此实例才能动态创建多个日志文件
            //var _key = $"{jobName}_{level.GetHashCode()}";  
            //// 确保 Loggers 字典中不会添加重复的键
            //lock (locker)
            //{
            //    if (!Loggers.ContainsKey(_key))
            //    {
            //        ILoggerRepository _repository = LoggerManager.CreateRepository(_key);
            //        BasicConfigurator.Configure(_repository, appender);
            //        LogManager.GetLogger(_repository.Name, _key);
            //        Loggers.Add(_key, LogManager.GetLogger(_key));
            //    }
            //}

            //RollingFileAppender appender = new RollingFileAppender();
            //appender.Layout = patternLayout;
            //// 使用读取到的路径来设置 appender 的 File 属性  
            //appender.File = Path.Combine(logDirectory, jobName, $"{level}_{DateTime.Now.ToString("yyyyMMdd")}.txt");
            //appender.AppendToFile = true;
            //appender.RollingStyle = RollingFileAppender.RollingMode.Date;
            //appender.DatePattern = "yyyyMMdd"; // 设置滚动文件的日期格式
            //appender.StaticLogFileName = false;  
            //appender.ActivateOptions();



            var _key = $"{jobName}_{level.GetHashCode()}";
            // 确保 Loggers 字典中不会添加重复的键
            lock (locker)
            {
                if (!Loggers.ContainsKey(_key))
                {
                    Logger logger = (Logger)hierarchy.GetLogger(_key);
                    logger.AddAppender(appender);
                    logger.Level = hierarchy.Root.Level;
                    Loggers.Add(_key, LogManager.GetLogger(_key));
                }
            }
        }

        public enum LogLevel
        {
            Debug,
            Info,
            Error
        }
    }
View Code

调用:

 var _Nlogger = new NLogger(typeof(TestExcuteJob).Name + "/你的路径"));

  

标签:log4net,Loggers,string,写入,jobName,patternLayout,key,日志,appender
From: https://www.cnblogs.com/systemkk/p/18140048

相关文章

  • MySQL的三大日志及事务
    标题其实不太准确,应该是MySQL的binlog,InnoDB的redolog和undolog 事务的四大特征:ACID, 其中原子性(A)、隔离性(I)和持久性(D)是手段, 一致性(C)是目标。Atomicity   原子性 ==》由undolog实现Consistency一致性 ==》最终的目标,由AID共同来保证Isolation   ......
  • ros 日志
    ros网址http://wiki.ros.org/roscpp/Overview/Logginghttps://www.jianshu.com/p/8d23b4c12f6f日志消息等级debuginfowarnerrorfatal日志消息查看/更改工具rqt_console查看日志rqt_logger_level更改日志等级命令行更改日志等级:rosservicecall/node-name/set_logg......
  • 解决ELK日志被截断的问题
    问题1importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassTestLogger{privatestaticLoggerlogger=LoggerFactory.getLogger(TestLogger.class);publicstaticvoidmain(String[]args){Stringtest="<xml&g......
  • Cmocka 单元测试日志记录
    isbs_doc/release/ipg/../ut跑例(24.4.15)ut测试不通过在isbs_doc文件夹git分支release/ipg中对ut进行跑例测试通过gitcloneisbs_doc文件夹到本地切换到release/ipg分支在#164中找到关于cmocka单元测试的ut文件夹在终端MSYS2-Mingw64直接切换到该目......
  • 案例二十一备份30天之前的日志并压缩到指定目录下
    #!/bin/bash#备份目录info_backdir=/backup/log/info/`date-d"30dayago"+%F|awk-F"-"'{print$1"-"$2}'`error_backdir=/backup/log/error/`date-d"30dayago"+%F|awk-F"-"'{print$1"......
  • C / C++ 文件简单混编 + 轻量级日志系统使用
    在项目工程里面,不一定全部是c或者c++文件,有时候是混合一起,这个时候如果使用makefile编译的话,就要考虑兼容两种类型的文件编译了;实战经验如下:根据自己的风格制作响应的打印和日志记录,makefile编写如下:CC=gccCPP=g++#文件夹路径ROOTPATH=.INCLUDE=-I./cfg/inc-I$(......
  • Feign日志 - 自定义 info级别打印
    背景由于feign,默认只有debug的level,才能打印出日志。不太符合一般项目的loginfolevel的约定。因此决定自定义feign的log打印。目的在infolevel下,可以打印feign日志寻找线索打开openfeign的核心包目录寻找log相关类 feign-1.png通过FeignLoggerfactor......
  • 如何在 Pytest 中添加日志记录
    前言在编写和运行测试时,对于调试和排查问题,添加日志记录是一种非常有用的技术。Pytest是一个流行的Python测试框架,开发者通过pytest可以轻松地编写和运行各种测试。本文将介绍如何在Pytest中添加日志记录,以便更好地理解测试执行过程中的细节和问题。pytest.ini我们之前有......
  • 如何在 Pytest 中添加日志记录
    前言在编写和运行测试时,对于调试和排查问题,添加日志记录是一种非常有用的技术。Pytest是一个流行的Python测试框架,开发者通过pytest可以轻松地编写和运行各种测试。本文将介绍如何在Pytest中添加日志记录,以便更好地理解测试执行过程中的细节和问题。pytest.ini我们之前有......
  • 资源池化基于DORADO双集群搭建指南(非日志合一)
    资源池化基于DORADO双集群搭建指南----非日志合一10.10.10前置条件工程已完成代码编译,或者。主备存储已经挂载磁阵LUN设备,并且已经安装ultrapath多路径软件,磁阵设备可用。限制条件两套正常的dorado存储,需要搭建两套资源池化集群。基于资源池化本地日志和同步复制共享xlog两......