public void TestAppender1() { log = (Logger)Utils.GetLogger("test").Logger; CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender1"; log.AddAppender(a1); IEnumerator enumAppenders = ((IEnumerable)log.Appenders).GetEnumerator(); Assert.IsTrue(enumAppenders.MoveNext()); CountingAppender aHat = (CountingAppender)enumAppenders.Current; Assert.AreEqual(a1, aHat); }
public void TestDisable1() { CountingAppender caRoot = new CountingAppender(); Logger root = ((Repository.Hierarchy.Hierarchy)Utils.GetRepository()).Root; root.AddAppender(caRoot); Repository.Hierarchy.Hierarchy h = ((Repository.Hierarchy.Hierarchy)Utils.GetRepository()); h.Threshold = Level.Info; h.Configured = true; Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 0); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 1); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 2); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 3); h.Threshold = Level.Warn; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 3); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 4); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 5); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); h.Threshold = Level.Off; root.Log(Level.Debug, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Info, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Warn, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Error, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); root.Log(Level.Fatal, MSG, null); Assert.AreEqual(caRoot.Counter, 6); }
public LogSpy(ILog log, Level level) { logger = log.Logger as Logger; if (logger == null) { throw new InvalidOperationException("Unable to get the logger"); } // Change the log level to DEBUG and temporarily save the previous log level prevLogLevel = logger.Level; logger.Level = level; // Add a new MemoryAppender to the logger. appender = new MemoryAppender(); logger.AddAppender(appender); }
private void EnsureConsoleAppender() { if (_consoleAppender != null) { return; } var consoleAppenderName = "ConsoleAppender"; _consoleAppender = (AppenderSkeleton)RootLogger.GetAppender(consoleAppenderName); if (_consoleAppender == null) { _consoleAppender = GetConfiguredAppender(consoleAppenderName) ?? CreateAppender(consoleAppenderName); RootLogger.AddAppender(_consoleAppender); } }
internal static ILog SetupModLog(string path, string name, BetterLogSettings settings) { if (!settings.Enabled) { return(null); } var log = Logger.GetLogger(name); var appender = new BetterLog(path, settings); Logger.AddAppender(name, appender); Logger.SetLoggerLevel(name, settings.Level); //Logger.IsLogging = true; // workaround for logging being disabled in debug build?!? return(log); }
public RichEditLogOutPut(string libname, RichTextBox richTextBox, int maxLines, int minLines, int kepLines) { this.a = new LogRichEditAppender(richTextBox, maxLines, minLines, kepLines, @"%d{HH:mm:ss.fff} %-10p %m %n"); Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy; if (hierarchy != null) { Logger loog = hierarchy.GetLogger(libname) as log4net.Repository.Hierarchy.Logger; if (loog != null) { loog.AddAppender(this.a); } } a.Threshold = log4net.Core.Level.Info; }
internal override ILogger GetCustomLogger(string loggerName) { Logger logger = Repository.LoggerFactory.CreateLogger(Repository, loggerName); logger.Hierarchy = Repository; logger.Parent = Repository.Root; logger.Level = Level.Debug;//日志输出等级(默认) logger.Additivity = false; while (_appenderContainer.Count > 0) { _appenderContainer.TryDequeue(out var result); logger.AddAppender(result); } logger.Repository.Configured = true; return(logger); }
internal static BetterLogger SetupModLog(string path, string name, BetterLogSettings settings) { if (!settings.Enabled) { return(new BetterLogger(null, LogLevel.Error)); } var log = Logger.GetLogger(name); var appender = new BetterLog(path, settings); Logger.AddAppender(name, appender); Logger.SetLoggerLevel(name, settings.Level); var logger = new BetterLogger(log, settings.Level); return(logger); }
/// <summary> /// 使用日志的名字获取log4net对象,如果没有配置文件,则使用默认的配置创建对象并返回 /// </summary> /// <param name="loggerName">如果使用的是配置文件,则是<logger name="loggerName">标签中的 /// name属性的值</param> /// <param name="category"> /// 文件的上层文件夹,即类别,当使用默认配置时: /// <para>如果有值,则生成的日志路径为Log\{category}\{短时间}.log;</para> /// <para>如果没值,则生成的路径为Log\{短时间}.log</para> /// </param> /// <param name="additivity">该值指示子记录器是否继承其父级的appender。</param> /// <returns></returns> internal static ILog GetLogger(string loggerName, string category = null, bool additivity = false) { if (loggerContainer.ContainsKey(loggerName)) { return(loggerContainer[loggerName]); } if (UseConfig) { string path = ConfigPath; //首先判断根目录下是否有log4net.config文件 if (string.IsNullOrEmpty(path)) { path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + (@"\log4net.config"); } if (File.Exists(path)) { XmlConfigurator.ConfigureAndWatch(new FileInfo(path)); } } ILog log = LogManager.Exists(loggerName); if (UseConfig && log == null) { throw new Exception("获取对象失败,请指定正确的日志名或者配置文件!"); } if (log == null) { IAppender newAppender = GetNewFileApender(null, loggerName, category); Hierarchy repository = (Hierarchy)LogManager.GetRepository(); Logger logger = repository.LoggerFactory.CreateLogger(repository, loggerName); logger.Hierarchy = repository; logger.Parent = repository.Root; logger.Level = Level.Info; logger.Additivity = additivity; logger.AddAppender(newAppender); logger.Repository.Configured = true; log = new LogImpl(logger); } loggerContainer.TryAdd(loggerName, log); return(log); //return loggerContainer.GetOrAdd(loggerName, delegate (string name) //{ // ILog log= LogManager.Exists(loggerName); // return log; //}); }
public void Init(HttpApplication context) { // we need to make the check here because an HttpModule can be created more then // once in an application lifetime, so we should be careful not to add the counter // twice. Logger logger = (Logger)LogManager.GetLogger("NHibernate.SQL").Logger; lock (logger) { if (HasCountingAppender(logger) == false) { logger.AddAppender(new CountToContextItemsAppender()); logger.Level = logger.Hierarchy.LevelMap["DEBUG"]; } } context.EndRequest += new EventHandler(context_EndRequest); }
/// <summary> /// Sets the Appender that the ADK will use for logging. /// </summary> /// <param name="logger"></param> /// <param name="appender"></param> /// <param name="level"></param> private static void SetLogAppender(Logger logger, IAppender appender, Level level) { if (logger != null) { logger.RemoveAllAppenders(); logger.AddAppender(appender); logger.Repository.Threshold = level; logger.Repository.Configured = true; } else { throw new AdkException ("Unable to initialize log4net framework, ADK Logger is null", null); } }
public static ToSelfAppender StartAppending(string loggerName = "NHibernate.SQL", bool addStack = true) { var appender = new ToSelfAppender() { AddStack = addStack, LoggerName = loggerName }; Logger logger = (Logger)LogManager.GetLogger(loggerName).Logger; logger.Level = Level.All; logger.AddAppender(appender); logger.Level = logger.Hierarchy.LevelMap["DEBUG"]; BasicConfigurator.Configure(logger.Repository); return(appender); }
/// <summary> /// Adding a logger /// </summary> /// <param name="Name">Namespace name of teh logger to be found</param> /// <param name="appender">Appender</param> /// <param name="level">Logging level ///Log level priority in descending order: ///FATAL = 1 show log -> FATAL ///ERROR = 2 show log -> FATAL ERROR ///WARN = 3 show log -> FATAL ERROR WARN ///INFO = 4 show log -> FATAL ERROR WARN INFO ///DEBUG = 5 show log -> FATAL ERROR WARN INFO DEBUG /// </param> public void AddLogger(string Name, IAppender appender, Level level) { try { _HierarchyLogger.Configured = false; Logger L = _HierarchyLogger.GetLogger(Name) as Logger; _Loggers.Add(L); L.Level = level; L.AddAppender(appender); _HierarchyLogger.Configured = true; _HierarchyLogger.RaiseConfigurationChanged(EventArgs.Empty); } catch (Exception e) { Console.WriteLine("appender error : " + e); } }
private ILog InitializeLog(string logFileName) { ILog logger = LogManager.GetLogger(logFileName); Logger logger2 = logger.Logger as Logger; if (logger2 != null) { logger2.AddAppender(this.CreateRollingFileAppender(logFileName)); } Logger logger3 = logger.Logger as Logger; if (logger3 != null) { logger3.Hierarchy.Configured = true; } return(logger); }
public virtual void TestAppendInClose() { ContainerLogAppender claAppender = new ContainerLogAppender(); claAppender.SetName("testCLA"); claAppender.SetLayout(new PatternLayout("%-5p [%t]: %m%n")); claAppender.SetContainerLogDir("target/testAppendInClose/logDir"); claAppender.SetContainerLogFile("syslog"); claAppender.SetTotalLogFileSize(1000); claAppender.ActivateOptions(); Logger claLog = Logger.GetLogger("testAppendInClose-catergory"); claLog.SetAdditivity(false); claLog.AddAppender(claAppender); claLog.Info(new _object_39(claLog)); claAppender.Close(); }
static void Main(string[] args) { ILayout simLayout = new SimpleLayout(); IAppender conAppender = new ConsoleAppender(simLayout); ILogger logger = new Logger(conAppender); logger.Error("Error parsing JSON"); logger.Info(string.Format("User {0} successfully registered.", "Pesho")); Console.WriteLine(new string('-', 20)); IFileAppender fileAppender = new FileAppender(simLayout); fileAppender.File = "log.txt"; logger.AddAppender(fileAppender); logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); Console.WriteLine(new string('-', 20)); foreach (IAppender appender in logger.Appenders) { appender.Layout = new XmlLayout(); } logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); Console.WriteLine(new string('-', 20)); foreach (IAppender appender in logger.Appenders) { appender.ReportLevelMinimum = Enums.ReportLevel.Error; } logger.Info("Everything seems fine"); logger.Warning("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); Console.WriteLine(new string('-', 20)); }
public SqlLogSpy() { ILog log = LogManager.GetLogger("NHibernate.SQL"); sqlLogger = log.Logger as Logger; if (sqlLogger == null) { throw new Exception("Unable to get the SQL logger"); } // Change the log level to DEBUG and temporarily save the previous log level prevLogLevel = sqlLogger.Level; sqlLogger.Level = Level.Debug; // Add a new MemoryAppender to the logger. appender = new MemoryAppender(); sqlLogger.AddAppender(appender); }
public static ILog GetCustomLogger(string loggerName, string category = null, bool additivity = false) { return(loggerContainer.GetOrAdd(loggerName, delegate(string name) { RollingFileAppender newAppender = GetNewFileApender(loggerName, GetFile(category, loggerName), MAX_SIZE_ROLL_BACKUPS, true, true, MAXIMUM_FILE_SIZE, RollingFileAppender.RollingMode.Composite, DATE_PATTERN, LAYOUT_PATTERN); log4net.Repository.Hierarchy.Hierarchy repository = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); Logger logger = repository.LoggerFactory.CreateLogger(repository, loggerName); logger.Hierarchy = repository; logger.Parent = repository.Root; logger.Level = GetLoggerLevel(LEVEL); logger.Additivity = additivity; logger.AddAppender(newAppender); logger.Repository.Configured = true; return new LogImpl(logger); })); }
public LoggerWatch(string libname, Level level, delegateShowLog view, int sleep) { log.Debug("开始日志 观察............"); this.libname = libname; this.sleep = sleep; this.view = view; ILoggerRepository[] al = LogManager.GetAllRepositories(); append = new log4net.Appender.MemoryAppender(); append.Threshold = getLevel(level); Hierarchy h = LogManager.GetRepository() as Hierarchy; Logger loog = h.GetLogger(libname) as log4net.Repository.Hierarchy.Logger; loog.AddAppender(append); logWatcher = new Thread(new ThreadStart(LogWatcher)); logWatcher.Start(); }
/// <summary> /// Parses the children of a logger element. /// </summary> /// <param name="catElement">The category element.</param> /// <param name="log">The logger instance.</param> /// <param name="isRoot">Flag to indicate if the logger is the root logger.</param> /// <remarks> /// <para> /// Parse the child elements of a <logger> element. /// </para> /// </remarks> protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) { // Remove all existing appenders from log. They will be // reconstructed if need be. log.RemoveAllAppenders(); foreach (XmlNode currentNode in catElement.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement)currentNode; if (currentElement.LocalName == APPENDER_REF_TAG) { IAppender appender = FindAppenderByReference(currentElement); string refName = currentElement.GetAttribute(REF_ATTR); if (appender != null) { LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); log.AddAppender(appender); } else { LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); } } else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) { ParseLevel(currentElement, log, isRoot); } else { SetParameter(currentElement, log); } } } IOptionHandler optionHandler = log as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } }
public string AttachMemoryLogger() { // Set up a memory logger against the root, to intercept at All Levels String name = String.Format("MA{0}", DateTime.UtcNow); MemoryAppender memoryAppender = new MemoryAppender(); memoryAppender.Name = name; memoryAppender.Layout = new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %message (%logger{1}:%line)%n"); memoryAppender.Threshold = Level.All; memoryAppender.ActivateOptions(); Logger root = LoggingHierarchy.Root; root.AddAppender(memoryAppender); root.Repository.Configured = true; return(name); }
public void TestAdditivity1() { Logger a = (Logger)Utils.GetLogger("a").Logger; Logger ab = (Logger)Utils.GetLogger("a.b").Logger; CountingAppender ca = new CountingAppender(); a.AddAppender(ca); a.Repository.Configured = true; Assert.AreEqual(ca.Counter, 0); ab.Log(Level.Debug, MSG, null); Assert.AreEqual(ca.Counter, 1); ab.Log(Level.Info, MSG, null); Assert.AreEqual(ca.Counter, 2); ab.Log(Level.Warn, MSG, null); Assert.AreEqual(ca.Counter, 3); ab.Log(Level.Error, MSG, null); Assert.AreEqual(ca.Counter, 4); }
/// <summary> /// Initializes a new instance of the <see cref="LockResourceLogger" /> class. /// </summary> /// <param name="resourceId">The resource identifier.</param> public LockResourceLogger(string resourceId) { Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); // Create a new logger for this resource ID _logger = hierarchy.GetLogger($"{_rootLoggerName}.{resourceId}") as Logger; // Find the template logger and its appender and create a copy for this resource Logger templateLogger = hierarchy.GetLogger(_templateLoggerName) as Logger; if (templateLogger?.Appenders.Count > 0) { if (templateLogger.Appenders[0] is RollingFileAppender templateAppender) { RollingFileAppender appender = CreateResourceAppender(templateAppender, resourceId); _logger.AddAppender(appender); } } }
public EngineLogger(string name) { RollingFileAppender rollingFileAppender = new RollingFileAppender(); rollingFileAppender.File = string.Format("logs/{0}.dat", name); rollingFileAppender.AppendToFile = true; rollingFileAppender.MaxSizeRollBackups = 20; rollingFileAppender.MaximumFileSize = "1000KB"; ILayout layout = new PatternLayout("%date [%thread] %message%newline"); rollingFileAppender.Layout = layout; rollingFileAppender.Name = name; rollingFileAppender.ActivateOptions(); Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy; Logger logger = hierarchy.GetLogger(name) as Logger; logger.AddAppender(rollingFileAppender); this.logger = LogManager.GetLogger(name); }
/// <summary> /// Return the log entry messages created by the logger specified by /// <paramref name="loggerName"/> while executing the delegate <paramref /// name="operation"/> /// </summary> public static IList <string> Log(string loggerName, Proc operation) { Logger logger = (Logger)LogManager.GetLogger(loggerName).Logger; InMemoryMessageAppender appender = new InMemoryMessageAppender(); try { logger.AddAppender(appender); logger.Level = logger.Hierarchy.LevelMap["DEBUG"]; using (new ActiveLoggerFilterScope(loggerName)) { operation(); } return(appender.Messages); } finally { logger.RemoveAppender(appender); } }
/// <summary> /// Setups application logging /// <param name="fileName">Log file name</param> /// <param name="needDebug">If true, writes debug info to log file</param> /// </summary> public static void Log4Setup(string fileName, bool needDebug) { if (!LogManager.GetRepository().Configured) { Logger root = ((Hierarchy)LogManager.GetRepository()).Root; root.Level = needDebug ? Level.All : Level.Info; var fa = new RollingFileAppender(); fa.Layout = new PatternLayout("%d{dd.MM.yyyy HH:mm:ss} (%logger) %-5p %m%n"); fa.File = fileName; fa.ImmediateFlush = true; fa.AppendToFile = true; fa.RollingStyle = RollingFileAppender.RollingMode.Size; fa.MaxSizeRollBackups = 1; fa.MaximumFileSize = "10M"; fa.ActivateOptions(); root.AddAppender(fa); LogManager.GetRepository().Configured = true; } }
/// <summary> /// Initializes a new instance of the <see cref="SumoLogicAppenderTest"/> class. /// </summary> public SumoLogicAppenderTest() { messagesHandler = new MockHttpMessageHandler(); sumoLogicAppender = new SumoLogicAppender(null, messagesHandler); sumoLogicAppender.Url = "http://www.fakeadress.com"; sumoLogicAppender.SourceName = "SumoLogicAppenderSourceName"; sumoLogicAppender.SourceCategory = "SumoLogicAppenderSourceCategory"; sumoLogicAppender.SourceHost = "SumoLogicAppenderSourceHost"; sumoLogicAppender.Layout = new PatternLayout("-- %m%n"); sumoLogicAppender.UseConsoleLog = true; sumoLogicAppender.ActivateOptions(); log4netLog = LogManager.GetLogger(typeof(SumoLogicAppenderTest)); log4netLogger = (Logger)log4netLog.Logger; log4netLogger.Additivity = false; log4netLogger.Level = Level.All; log4netLogger.RemoveAllAppenders(); log4netLogger.AddAppender(sumoLogicAppender); log4netLogger.Repository.Configured = true; }
private static void Main(string[] args) { var appenderCount = int.Parse(Console.ReadLine()); var logger = new Logger(); for (var i = 0; i < appenderCount; i++) { var input = Console.ReadLine().Split(); var appenderName = input[0]; var layoutName = input[1]; var level = ThresholdLevel.Info; if (input.Length == 3) { level = (ThresholdLevel)Enum.Parse(typeof(ThresholdLevel), input[2], true); } var type = Type.GetType("Problem_01.Logger.Models." + layoutName); var layout = Activator.CreateInstance(type); type = Type.GetType("Problem_01.Logger.Models." + appenderName); var appender = (IAppender)Activator.CreateInstance(type, new object[] { layout, level }); logger.AddAppender(appender); } while (true) { var line = Console.ReadLine(); if (line == "END") { break; } var input = line.Split('|'); var date = DateTime.Parse(input[1]); var level = (ThresholdLevel)Enum.Parse(typeof(ThresholdLevel), input[0], true); var message = input[2]; logger.LogMessage(date, level, message); } Console.WriteLine(logger); }
public static void TestConfig1() { var hierarchy = LogManager.GetRepository(); hierarchy.Configured = false; Logger logger = (Logger)hierarchy.GetLogger("Test1"); //logger.AddAppender(new MyLog4NetAppender()); logger.AddAppender(new MyLog4NetAppender()); hierarchy.Configured = true; //logger. //var appenders = test.GetAppenders(); //test.ConfigurationMessages.add //new log4net.log var log = LogManager.GetLogger("Test"); log.Debug(new TestMessage() { Name = "111", Test = "222" }); }
/// <exception cref="System.IO.IOException"/> private void ConfigureAuditLogs() { // Shutdown the LogManager to release all logger open file handles. // Unfortunately, Apache commons logging library does not provide // means to release underlying loggers. For additional info look up // commons library FAQ. LogManager.Shutdown(); FilePath file = new FilePath(auditLogFile); if (file.Exists()) { NUnit.Framework.Assert.IsTrue(file.Delete()); } Logger logger = ((Log4JLogger)FSNamesystem.auditLog).GetLogger(); // disable logging while the cluster startup preps files logger.SetLevel(Level.Off); PatternLayout layout = new PatternLayout("%m%n"); RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile); logger.AddAppender(appender); }