用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