public void Configure(XmlElement element) { if ((element != null) && (this.m_hierarchy != null)) { if (element.LocalName != "log4net") { LogLog.Error(declaringType, "Xml element is - not a <log4net> element."); } else { if (!LogLog.EmitInternalMessages) { string argValue = element.GetAttribute("emitDebug"); LogLog.Debug(declaringType, "emitDebug attribute [" + argValue + "]."); if ((argValue.Length > 0) && (argValue != "null")) { LogLog.EmitInternalMessages = OptionConverter.ToBoolean(argValue, true); } else { LogLog.Debug(declaringType, "Ignoring emitDebug attribute."); } } if (!LogLog.InternalDebugging) { string argValue = element.GetAttribute("debug"); LogLog.Debug(declaringType, "debug attribute [" + argValue + "]."); if ((argValue.Length > 0) && (argValue != "null")) { LogLog.InternalDebugging = OptionConverter.ToBoolean(argValue, true); } else { LogLog.Debug(declaringType, "Ignoring debug attribute."); } string str4 = element.GetAttribute("configDebug"); if ((str4.Length > 0) && (str4 != "null")) { LogLog.Warn(declaringType, "The \"configDebug\" attribute is deprecated."); LogLog.Warn(declaringType, "Use the \"debug\" attribute instead."); LogLog.InternalDebugging = OptionConverter.ToBoolean(str4, true); } } ConfigUpdateMode merge = ConfigUpdateMode.Merge; string attribute = element.GetAttribute("update"); if ((attribute != null) && (attribute.Length > 0)) { try { merge = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), attribute); } catch { LogLog.Error(declaringType, "Invalid update attribute value [" + attribute + "]"); } } LogLog.Debug(declaringType, "Configuration update mode [" + merge.ToString() + "]."); if (merge == ConfigUpdateMode.Overwrite) { this.m_hierarchy.ResetConfiguration(); LogLog.Debug(declaringType, "Configuration reset before reading config."); } IEnumerator enumerator = element.ChildNodes.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlNode current = (XmlNode)enumerator.Current; if (current.NodeType == XmlNodeType.Element) { XmlElement loggerElement = (XmlElement)current; if (loggerElement.LocalName == "logger") { this.ParseLogger(loggerElement); continue; } if (loggerElement.LocalName == "category") { this.ParseLogger(loggerElement); continue; } if (loggerElement.LocalName == "root") { this.ParseRoot(loggerElement); continue; } if (loggerElement.LocalName == "renderer") { this.ParseRenderer(loggerElement); continue; } if (loggerElement.LocalName != "appender") { this.SetParameter(loggerElement, this.m_hierarchy); } } } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } string str6 = element.GetAttribute("threshold"); LogLog.Debug(declaringType, "Hierarchy Threshold [" + str6 + "]"); if ((str6.Length > 0) && (str6 != "null")) { Level level = (Level)this.ConvertStringTo(typeof(Level), str6); if (level != null) { this.m_hierarchy.Threshold = level; } else { LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + str6 + "] (with acceptable conversion types)"); } } } } }
/// <summary> /// Parses an appender element. /// </summary> /// <param name="appenderElement">The appender element.</param> /// <returns>The appender instance or <c>null</c> when parsing failed.</returns> /// <remarks> /// <para> /// Parse an XML element that represents an appender and return /// the appender instance. /// </para> /// </remarks> protected IAppender ParseAppender(XmlElement appenderElement) { string appenderName = appenderElement.GetAttribute(NAME_ATTR); string typeName = appenderElement.GetAttribute(TYPE_ATTR); LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); try { #if NETSTANDARD1_3 IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, typeName, true, true)); #else IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); #endif appender.Name = appenderName; foreach (XmlNode currentNode in appenderElement.ChildNodes) { /* We're only interested in Elements */ if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement)currentNode; // Look for the appender ref tag if (currentElement.LocalName == APPENDER_REF_TAG) { string refName = currentElement.GetAttribute(REF_ATTR); IAppenderAttachable appenderContainer = appender as IAppenderAttachable; if (appenderContainer != null) { LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); IAppender referencedAppender = FindAppenderByReference(currentElement); if (referencedAppender != null) { appenderContainer.AddAppender(referencedAppender); } } else { LogLog.Error(declaringType, "Requesting attachment of appender named [" + refName + "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable."); } } else { // For all other tags we use standard set param method SetParameter(currentElement, appender); } } } IOptionHandler optionHandler = appender as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]"); return(appender); } catch (Exception ex) { // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); return(null); } }
/// <summary> /// Configure the hierarchy by parsing a DOM tree of XML elements. /// </summary> /// <param name="element">The root element to parse.</param> /// <remarks> /// <para> /// Configure the hierarchy by parsing a DOM tree of XML elements. /// </para> /// </remarks> public void Configure(XmlElement element) { if (element == null || m_hierarchy == null) { return; } string rootElementName = element.LocalName; if (rootElementName != CONFIGURATION_TAG) { LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); return; } if (!LogLog.EmitInternalMessages) { // Look for a emitDebug attribute to enable internal debug string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR); LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "]."); if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null") { LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true); } else { LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute."); } } if (!LogLog.InternalDebugging) { // Look for a debug attribute to enable internal debug string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "]."); if (debugAttribute.Length > 0 && debugAttribute != "null") { LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); } else { LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); if (confDebug.Length > 0 && confDebug != "null") { LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); } } // Default mode is merge ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; // Look for the config update attribute string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) { // Parse the attribute try { configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); } catch { LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); } } // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); // Only reset configuration if overwrite flag specified if (configUpdateMode == ConfigUpdateMode.Overwrite) { // Reset to original unset configuration m_hierarchy.ResetConfiguration(); LogLog.Debug(declaringType, "Configuration reset before reading config."); } /* Building Appender objects, placing them in a local namespace * for future reference */ /* Process all the top level elements */ foreach (XmlNode currentNode in element.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement)currentNode; if (currentElement.LocalName == LOGGER_TAG) { ParseLogger(currentElement); } else if (currentElement.LocalName == CATEGORY_TAG) { // TODO: deprecated use of category ParseLogger(currentElement); } else if (currentElement.LocalName == ROOT_TAG) { ParseRoot(currentElement); } else if (currentElement.LocalName == RENDERER_TAG) { ParseRenderer(currentElement); } else if (currentElement.LocalName == APPENDER_TAG) { // We ignore appenders in this pass. They will // be found and loaded if they are referenced. } else { // Read the param tags and set properties on the hierarchy SetParameter(currentElement, m_hierarchy); } } } // Lastly set the hierarchy threshold string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); if (thresholdStr.Length > 0 && thresholdStr != "null") { Level thresholdLevel = (Level)ConvertStringTo(typeof(Level), thresholdStr); if (thresholdLevel != null) { m_hierarchy.Threshold = thresholdLevel; } else { LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); } } // Done reading config }
/// <summary> /// Creates a new repository for the specified repository. /// </summary> /// <param name="repositoryName">The repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>. /// If this param is <see langword="null" /> then the default repository type is used.</param> /// <returns>The new repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(string)"/> with the /// same repository specified will return the same repository instance. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception> /// <exception cref="LogException"><paramref name="repositoryName"/> already exists.</exception> public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock (this) { ILoggerRepository rep = null; // First check that the repository does not exist rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep != null) { throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); } else { // Lookup an alias before trying to create the new repository ILoggerRepository aliasedRepository = m_alias2repositoryMap[repositoryName] as ILoggerRepository; if (aliasedRepository != null) { // Found an alias // Check repository type if (aliasedRepository.GetType() == repositoryType) { // Repository type is compatible LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); rep = aliasedRepository; // Store in map m_name2repositoryMap[repositoryName] = rep; } else { // Invalid repository type for alias LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]. Requested repository type [" + repositoryType.FullName + "] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); // We now drop through to create the repository without aliasing } } // If we could not find an alias if (rep == null) { LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); // Call the no arg constructor for the repositoryType rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); // Set the name of the repository rep.Name = repositoryName; // Store in map m_name2repositoryMap[repositoryName] = rep; // Notify listeners that the repository has been created OnLoggerRepositoryCreatedEvent(rep); } } return(rep); } }
/// <summary> /// Configures the repository using information from the assembly. /// </summary> /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes which define the configuration for the repository.</param> /// <param name="repository">The repository to configure.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { // Sort the ConfiguratorAttributes in priority order Array.Sort(configAttributes); // Delegate to the attribute the job of configuring the repository foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes) { if (configAttr != null) { try { configAttr.Configure(assembly, repository); } catch (Exception ex) { LogLog.Error(declaringType, "Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex); } } } } if (repository.Name == DefaultRepositoryName) { // Try to configure the default repository using an AppSettings specified config file // Do this even if the repository has been configured (or claims to be), this allows overriding // of the default config files etc, if that is required. string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch (Exception ex) { LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex); } string repositoryConfigFilePath = repositoryConfigFile; if (applicationBaseDirectory != null) { repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile); } // Determine whether to watch the file or not based on an app setting value: bool watchRepositoryConfigFile = false; #if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); #else { string watch = SystemInfo.GetAppSetting("log4net.Config.Watch"); if (watch != null && watch.Length > 0) { try { watchRepositoryConfigFile = Boolean.Parse(watch); } catch (FormatException) { // simply not a Boolean } } } #endif if (watchRepositoryConfigFile) { // As we are going to watch the config file it is required to resolve it as a // physical file system path pass that in a FileInfo object to the Configurator FileInfo repositoryConfigFileInfo = null; try { repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); } catch (Exception ex) { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex); } try { LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]"); XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo); } catch (Exception ex) { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex); } } else { // As we are not going to watch the config file it is easiest to just resolve it as a // URI and pass that to the Configurator Uri repositoryConfigUri = null; try { repositoryConfigUri = new Uri(repositoryConfigFilePath); } catch (Exception ex) { LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); } if (repositoryConfigUri != null) { LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); try { // TODO: Support other types of configurator XmlConfigurator.Configure(repository, repositoryConfigUri); } catch (Exception ex) { LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); } } } } } }
/// <summary> /// Attempt to load configuration from a URI /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) { // Work out the full path to the config file Uri fullPath2ConfigFile = null; // Select the config file if (m_configFile == null || m_configFile.Length == 0) { if (m_configFileExtension == null || m_configFileExtension.Length == 0) { string systemConfigFilePath = null; try { systemConfigFilePath = SystemInfo.ConfigurationFileLocation; } catch (Exception ex) { LogLog.Error( "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); } if (systemConfigFilePath != null) { var systemConfigFileUri = new Uri(systemConfigFilePath); // Use the default .config file for the AppDomain fullPath2ConfigFile = systemConfigFileUri; } } else { // Force the extension to start with a '.' if (m_configFileExtension[0] != '.') { m_configFileExtension = "." + m_configFileExtension; } string systemConfigFilePath = null; try { systemConfigFilePath = SystemInfo.ConfigurationFileLocation; } catch (Exception ex) { LogLog.Error( "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); } if (systemConfigFilePath != null) { var builder = new UriBuilder(new Uri(systemConfigFilePath)); // Remove the current extension from the systemConfigFileUri path var path = builder.Path; var startOfExtension = path.LastIndexOf("."); if (startOfExtension >= 0) { path = path.Substring(0, startOfExtension); } path += m_configFileExtension; builder.Path = path; fullPath2ConfigFile = builder.Uri; } } } else { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch (Exception ex) { LogLog.Warn( "XmlConfiguratorAttribute: Exception getting ApplicationBaseDirectory. ConfigFile property path [" + m_configFile + "] will be treated as an absolute URI.", ex); } if (applicationBaseDirectory != null) { // Just the base dir + the config file fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), m_configFile); } else { fullPath2ConfigFile = new Uri(m_configFile); } } if (fullPath2ConfigFile != null) { if (fullPath2ConfigFile.IsFile) { // The m_configFile could be an absolute local path, therefore we have to be // prepared to switch back to using FileInfos here ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); } else { if (m_configureAndWatch) { LogLog.Warn("XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); } XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); } } }
private void ThreadProc() { while (true) { lock (myLock) { if (State >= StateKind.Terminating) { return; } while (myAllDataProcessed || myPauseReasons.Count > 0) { if (State >= StateKind.Stopping) { return; } Monitor.Wait(myLock); if (State >= StateKind.Terminating) { return; } } //In case of only put requests, we could write Assertion.Assert(chunk.Ptr > 0, "chunk.Ptr > 0"); //But in case of clear, we could get "Wait + Put(full) + Clear + Put" before this line and 'chunkToProcess' will point to empty chunk. //RIDER-15223 while (myChunkToProcess.CheckEmpty(this)) //should never be endless, because `myAllDataProcessed` is 'false', that means that we MUST have ptr > 0 somewhere { myChunkToProcess = myChunkToProcess.Next; } if (myChunkToFill == myChunkToProcess) { //it's possible that next chuck is occupied by entry with seqN > acknowledgedSeqN GrowConditionally(); myChunkToFill = myChunkToProcess.Next; } ShrinkConditionally(myChunkToProcess); Assertion.Assert(myChunkToProcess.Ptr > 0, "chunkToProcess.Ptr > 0"); Assertion.Assert(myChunkToFill != myChunkToProcess && myChunkToFill.IsNotProcessed, "myChunkToFill != chunkToProcess && myChunkToFill.IsNotProcessed"); myProcessing = true; } long seqN = myChunkToProcess.IsNotProcessed ? 0 : myChunkToProcess.SeqN; try { myProcessor(myChunkToProcess.Data, 0, myChunkToProcess.Ptr, ref seqN); } catch (Exception e) { LogLog.Error(e); } finally { lock (myLock) { myProcessing = false; if (myChunkToProcess == null) { LogLog.Error($"{nameof(myChunkToProcess)} is null. State: {State}"); } else { myChunkToProcess.SeqN = seqN; myChunkToProcess = myChunkToProcess.Next; // Assertion.Assert(myChunkToProcess.IsNotProcessed, "chunkToProcess.IsNotProcessed"); not true in case of reprocessing if (myChunkToProcess.Ptr == 0) { myAllDataProcessed = true; } } } } } }
static private void InternalConfigure(ILoggerRepository repository, Stream configStream) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); if (configStream == null) { LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); } else { // Load the config file into a document XmlDocument doc = new XmlDocument(); try { #if (NETCF) // Create a text reader for the file stream XmlTextReader xmlReader = new XmlTextReader(configStream); #elif NET_2_0 // Allow the DTD to specify entity includes XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = false; // Create a reader over the input stream XmlReader xmlReader = XmlReader.Create(configStream, settings); #else // Create a validating reader around a text reader for the file stream XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream)); // Specify that the reader should not perform validation, but that it should // expand entity refs. xmlReader.ValidationType = ValidationType.None; xmlReader.EntityHandling = EntityHandling.ExpandEntities; #endif // load the data into the document doc.Load(xmlReader); } catch (Exception ex) { LogLog.Error(declaringType, "Error while loading XML configuration", ex); // The document is invalid doc = null; } if (doc != null) { LogLog.Debug(declaringType, "loading XML configuration"); // Configure using the 'log4net' element XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); if (configNodeList.Count == 0) { LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted."); } else if (configNodeList.Count > 1) { LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted."); } else { InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); } } } }
/// <summary> /// Attempt to load configuration from a URI /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) { Uri uri = null; if (m_configFile == null || m_configFile.Length == 0) { if (m_configFileExtension == null || m_configFileExtension.Length == 0) { string text = null; try { text = SystemInfo.ConfigurationFileLocation; } catch (Exception exception) { LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", exception); } if (text != null) { uri = new Uri(text); } } else { if (m_configFileExtension[0] != '.') { m_configFileExtension = "." + m_configFileExtension; } string text2 = null; try { text2 = SystemInfo.ConfigurationFileLocation; } catch (Exception exception2) { LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", exception2); } if (text2 != null) { UriBuilder uriBuilder = new UriBuilder(new Uri(text2)); string text3 = uriBuilder.Path; int num = text3.LastIndexOf("."); if (num >= 0) { text3 = text3.Substring(0, num); } text3 = (uriBuilder.Path = text3 + m_configFileExtension); uri = uriBuilder.Uri; } } } else { string text5 = null; try { text5 = SystemInfo.ApplicationBaseDirectory; } catch (Exception exception3) { LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + m_configFile + "] will be treated as an absolute URI.", exception3); } uri = ((text5 == null) ? new Uri(m_configFile) : new Uri(new Uri(text5), m_configFile)); } if (!(uri != null)) { return; } if (uri.IsFile) { ConfigureFromFile(targetRepository, new FileInfo(uri.LocalPath)); return; } if (m_configureAndWatch) { LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); } XmlConfigurator.Configure(targetRepository, uri); }
public void Error(Type type, string message) { LogLog.Error(type, message); }
public void Error(Type type, string message, Exception ex) { LogLog.Error(type, message, ex); }
/// <summary> /// /// </summary> /// <param name="logLog"></param> /// <param name="ex"></param> public static void Error(Exception ex) { LogLog.Error(ex.GetType(), ex.Message); }
protected override void Append(LoggingEvent loggingEvent) { if (RavenClient == null) { RavenClient = new RavenClient(DSN) { Logger = Logger, Compression = CompressionEnabled, Environment = Environment, // If something goes wrong when sending the event to Sentry, make sure this is written to log4net's internal // log. See <add key="log4net.Internal.Debug" value="true"/> ErrorOnCapture = ex => LogLog.Error(typeof(SentryAppender), "[" + Name + "] " + ex.Message, ex) }; } var httpExtra = HttpExtra.GetHttpExtra(); object extra; if (httpExtra != null) { extra = new { Environment = new EnvironmentExtra(), Http = httpExtra }; } else { extra = new { Environment = new EnvironmentExtra() }; } var tags = _tagLayouts.ToDictionary(t => t.Name, t => (t.Layout.Format(loggingEvent) ?? "").ToString()); var exception = loggingEvent.ExceptionObject ?? loggingEvent.MessageObject as Exception; var level = Translate(loggingEvent.Level); if (loggingEvent.ExceptionObject != null) { // We should capture buth the exception and the message passed var @event = new SentryEvent(loggingEvent.RenderedMessage) { Extra = extra, Level = level, Tags = tags }; RavenClient.Capture(@event); } else if (loggingEvent.MessageObject is Exception) { // We should capture the exception with no custom message var @event = new SentryEvent(exception) { Extra = extra, Level = level, Tags = tags }; RavenClient.Capture(@event); } else { // Just capture message var message = loggingEvent.RenderedMessage; if (message != null) { var @event = new SentryEvent(loggingEvent.RenderedMessage) { Extra = extra, Level = level, Tags = tags }; RavenClient.Capture(@event); } } }
protected void SetParameter(XmlElement element, object target) { string attribute = element.GetAttribute("name"); if ((element.LocalName != "param") || ((attribute == null) || (attribute.Length == 0))) { attribute = element.LocalName; } Type targetType = target.GetType(); Type objA = null; PropertyInfo property = null; MethodInfo info2 = null; property = targetType.GetProperty(attribute, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if ((property != null) && property.CanWrite) { objA = property.PropertyType; } else { property = null; info2 = this.FindMethodInfo(targetType, attribute); if (info2 != null) { objA = info2.GetParameters()[0].ParameterType; } } if (objA == null) { string[] textArray1 = new string[] { "XmlHierarchyConfigurator: Cannot find Property [", attribute, "] to set object on [", target.ToString(), "]" }; LogLog.Error(declaringType, string.Concat(textArray1)); } else { string str2 = null; if (element.GetAttributeNode("value") != null) { str2 = element.GetAttribute("value"); } else if (element.HasChildNodes) { IEnumerator enumerator = element.ChildNodes.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlNode current = (XmlNode)enumerator.Current; if ((current.NodeType == XmlNodeType.CDATA) || (current.NodeType == XmlNodeType.Text)) { str2 = (str2 != null) ? (str2 + current.InnerText) : current.InnerText; } } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (str2 == null) { object obj3 = null; if (ReferenceEquals(objA, typeof(string)) && !this.HasAttributesOrElements(element)) { obj3 = string.Empty; } else { Type defaultTargetType = null; if (IsTypeConstructible(objA)) { defaultTargetType = objA; } obj3 = this.CreateObjectFromXml(element, defaultTargetType, objA); } if (obj3 == null) { LogLog.Error(declaringType, "Failed to create object to set param: " + attribute); } else if (property != null) { object[] objArray5 = new object[] { "Setting Property [", property.Name, "] to object [", obj3, "]" }; LogLog.Debug(declaringType, string.Concat(objArray5)); try { property.SetValue(target, obj3, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); } catch (TargetInvocationException exception4) { object[] objArray6 = new object[] { "Failed to set parameter [", property.Name, "] on object [", target, "] using value [", obj3, "]" }; LogLog.Error(declaringType, string.Concat(objArray6), exception4.InnerException); } } else if (info2 != null) { object[] objArray7 = new object[] { "Setting Collection Property [", info2.Name, "] to object [", obj3, "]" }; LogLog.Debug(declaringType, string.Concat(objArray7)); try { object[] parameters = new object[] { obj3 }; info2.Invoke(target, BindingFlags.InvokeMethod, null, parameters, CultureInfo.InvariantCulture); } catch (TargetInvocationException exception5) { object[] objArray9 = new object[] { "Failed to set parameter [", info2.Name, "] on object [", target, "] using value [", obj3, "]" }; LogLog.Error(declaringType, string.Concat(objArray9), exception5.InnerException); } } } else { try { IDictionary environmentVariables = Environment.GetEnvironmentVariables(); if (this.HasCaseInsensitiveEnvironment) { environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); } str2 = OptionConverter.SubstituteVariables(str2, environmentVariables); } catch (SecurityException) { LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); } Type type3 = null; string typeName = element.GetAttribute("type"); if ((typeName != null) && (typeName.Length > 0)) { try { Type c = SystemInfo.GetTypeFromString(typeName, true, true); string[] textArray2 = new string[] { "Parameter [", attribute, "] specified subtype [", c.FullName, "]" }; LogLog.Debug(declaringType, string.Concat(textArray2)); if (objA.IsAssignableFrom(c)) { objA = c; } else if (OptionConverter.CanConvertTypeTo(c, objA)) { type3 = objA; objA = c; } else { string[] textArray3 = new string[] { "subtype [", c.FullName, "] set on [", attribute, "] is not a subclass of property type [", objA.FullName, "] and there are no acceptable type conversions." }; LogLog.Error(declaringType, string.Concat(textArray3)); } } catch (Exception exception) { string[] textArray4 = new string[] { "Failed to find type [", typeName, "] set on [", attribute, "]" }; LogLog.Error(declaringType, string.Concat(textArray4), exception); } } object sourceInstance = this.ConvertStringTo(objA, str2); if ((sourceInstance != null) && (type3 != null)) { string[] textArray5 = new string[] { "Performing additional conversion of value from [", sourceInstance.GetType().Name, "] to [", type3.Name, "]" }; LogLog.Debug(declaringType, string.Concat(textArray5)); sourceInstance = OptionConverter.ConvertTypeTo(sourceInstance, type3); } if (sourceInstance == null) { object[] objArray4 = new object[] { "Unable to set property [", attribute, "] on object [", target, "] using value [", str2, "] (with acceptable conversion types)" }; LogLog.Warn(declaringType, string.Concat(objArray4)); } else if (property != null) { string[] textArray6 = new string[] { "Setting Property [", property.Name, "] to ", sourceInstance.GetType().Name, " value [", sourceInstance.ToString(), "]" }; LogLog.Debug(declaringType, string.Concat(textArray6)); try { property.SetValue(target, sourceInstance, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); } catch (TargetInvocationException exception2) { object[] objArray1 = new object[] { "Failed to set parameter [", property.Name, "] on object [", target, "] using value [", sourceInstance, "]" }; LogLog.Error(declaringType, string.Concat(objArray1), exception2.InnerException); } } else if (info2 != null) { string[] textArray7 = new string[] { "Setting Collection Property [", info2.Name, "] to ", sourceInstance.GetType().Name, " value [", sourceInstance.ToString(), "]" }; LogLog.Debug(declaringType, string.Concat(textArray7)); try { object[] parameters = new object[] { sourceInstance }; info2.Invoke(target, BindingFlags.InvokeMethod, null, parameters, CultureInfo.InvariantCulture); } catch (TargetInvocationException exception3) { object[] objArray3 = new object[] { "Failed to set parameter [", attribute, "] on object [", target, "] using value [", sourceInstance, "]" }; LogLog.Error(declaringType, string.Concat(objArray3), exception3.InnerException); } } } } }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_loggingTask != null) { if (!(_loggingTask.IsCanceled || _loggingTask.IsCompleted || _loggingTask.IsFaulted)) { try { CompleteSubscriberTask(); } catch (Exception ex) { LogLog.Error(ThisType, "Exception Completing Subscriber Task in Dispose Method", ex); } } try { _loggingTask.Dispose(); } catch (Exception ex) { LogLog.Error(ThisType, "Exception Disposing Logging Task", ex); } finally { _loggingTask = null; } } if (_loggingEvents != null) { try { _loggingEvents.Dispose(); } catch (Exception ex) { LogLog.Error(ThisType, "Exception Disposing BlockingCollection", ex); } finally { _loggingEvents = null; } } if (_loggingCancelationTokenSource != null) { try { _loggingCancelationTokenSource.Dispose(); } catch (Exception ex) { LogLog.Error(ThisType, "Exception Disposing CancellationTokenSource", ex); } finally { _loggingCancelationTokenSource = null; } } } _disposed = true; } }
/// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// URI. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configUri">A URI to load the XML configuration from.</param> /// <remarks> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c> Logging</c> that holds /// the configuration data. /// </para> /// <para> /// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified. /// </para> /// </remarks> static public void Configure(ILoggerRepository repository, Uri configUri) { LogLog.Trace("XmlConfigurator: configuring repository [" + repository.Name + "] using URI [" + configUri + "]"); if (configUri == null) { LogLog.Error("XmlConfigurator: Configure called with null 'configUri' parameter"); } else { if (configUri.IsFile) { // If URI is local file then call Configure with FileInfo Configure(repository, new FileInfo(configUri.LocalPath)); } else { // NETCF dose not support WebClient WebRequest configRequest = null; try { configRequest = WebRequest.Create(configUri); } catch (Exception ex) { LogLog.Error("XmlConfigurator: Failed to create WebRequest for URI [" + configUri + "]", ex); } if (configRequest != null) { #if !NETCF // authentication may be required, set client to use default credentials try { configRequest.Credentials = CredentialCache.DefaultCredentials; } catch { // ignore security exception LogLog.Warn("Exception while trying to get the systems credentials"); } #endif try { WebResponse response = configRequest.GetResponse(); if (response != null) { try { // Open stream on config URI using (Stream configStream = response.GetResponseStream()) { Configure(repository, configStream); } } finally { response.Close(); } } } catch (Exception ex) { LogLog.Error("XmlConfigurator: Failed to request config from URI [" + configUri + "]", ex); } } } } }
/// <summary> /// Attempt to load configuration from the local file system /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) { // Work out the full path to the config file string fullPath2ConfigFile = null; // Select the config file if (m_configFile == null || m_configFile.Length == 0) { if (m_configFileExtension == null || m_configFileExtension.Length == 0) { // Use the default .config file for the AppDomain try { fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; } catch (Exception ex) { LogLog.Error( "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); } } else { // Force the extension to start with a '.' if (m_configFileExtension[0] != '.') { m_configFileExtension = "." + m_configFileExtension; } string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch (Exception ex) { LogLog.Error( "XmlConfiguratorAttribute: Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); } if (applicationBaseDirectory != null) { fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension); } } } else { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch (Exception ex) { LogLog.Warn( "XmlConfiguratorAttribute: Exception getting ApplicationBaseDirectory. ConfigFile property path [" + m_configFile + "] will be treated as an absolute path.", ex); } if (applicationBaseDirectory != null) { // Just the base dir + the config file fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile); } else { fullPath2ConfigFile = m_configFile; } } if (fullPath2ConfigFile != null) { ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); } }
/// <summary> /// Get the count of events /// </summary> public static string EventCount( string parameters, IEnumerable <LoggingEvent> events, long loggingEventsLost) { if (string.IsNullOrEmpty(parameters) || "total".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { return(events.LongCount().ToString()); } else if ("triggering".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { return(events .Where(e => e.Properties[HtmlSmtpAppender.IsTriggerLoggingEvent] != null) .LongCount() .ToString()); } else if ("lost".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { return(loggingEventsLost.ToString()); } else if ("nontriggering".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { return(events .Where(e => e.Properties[HtmlSmtpAppender.IsTriggerLoggingEvent] == null) .LongCount() .ToString()); } else if (Regex.IsMatch(parameters, @"\d+")) { int level = int.Parse(parameters); return(events.Where(e => e.Level.Value == level).LongCount().ToString()); } else if (Enumerable.Any <Level>(LevelUtils.All, e => e.Name.Equals(parameters, StringComparison.InvariantCultureIgnoreCase))) { return(events .Where(e => e.Level.Name.Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) .LongCount() .ToString()); } else if ("class.unrecoverable".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { // Critical < level <= Off return(events.Where(e => e.Level.Value > Level.Critical.Value).LongCount().ToString()); } else if ("class.recoverable".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { // Notice < level <= Critical return(events .Where(e => e.Level.Value > Level.Notice.Value && e.Level.Value <= Level.Critical.Value) .LongCount() .ToString()); } else if ("class.information".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { // Debug < level <= Notice return(events .Where(e => e.Level.Value > Level.Debug.Value && e.Level.Value <= Level.Notice.Value) .LongCount() .ToString()); } else if ("class.debug".Equals(parameters, StringComparison.InvariantCultureIgnoreCase)) { // level <= Debug return(events.Where(e => e.Level.Value <= Level.Debug.Value).LongCount().ToString()); } else { LogLog.Error( typeof(StringFormatterUtil), string.Format("Invalid event count parameter '{0}'", parameters)); return(""); } }
/// <summary> /// Configures the repository using information from the assembly. /// </summary> /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes which define the configuration for the repository.</param> /// <param name="repository">The repository to configure.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { // Sort the ConfiguratorAttributes in priority order Array.Sort(configAttributes); // Delegate to the attribute the job of configuring the repository foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes) { if (configAttr != null) { try { configAttr.Configure(assembly, repository); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex); } } } } if (repository.Name == DefaultRepositoryName) { // Try to configure the default repository using an AppSettings specified config file // Do this even if the repository has been configured (or claims to be), this allows overriding // of the default config files etc, if that is required. string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch (Exception ex) { LogLog.Warn("DefaultRepositorySelector: Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex); } // As we are not going to watch the config file it is easiest to just resolve it as a // URI and pass that to the Configurator Uri repositoryConfigUri = null; try { if (applicationBaseDirectory != null) { // Resolve the config path relative to the application base directory URI repositoryConfigUri = new Uri(new Uri(applicationBaseDirectory), repositoryConfigFile); } else { repositoryConfigUri = new Uri(repositoryConfigFile); } } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); } if (repositoryConfigUri != null) { LogLog.Debug("DefaultRepositorySelector: Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); try { // TODO: Support other types of configurator XmlConfigurator.Configure(repository, repositoryConfigUri); } catch (Exception ex) { LogLog.Error("DefaultRepositorySelector: Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); } } } } }
public void Error(string message, Exception exception) { LogLog.Error(typeof(VerboseLogger), message, exception); }
/// <summary> /// Creates a new repository for the assembly specified. /// </summary> /// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryName">The name to assign to the created repository</param> /// <param name="readAssemblyAttributes">Set to <c>true</c> to read and apply the assembly attributes</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the repository to create can be overridden by specifying the /// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// <paramref name="repositoryAssembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="repositoryAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock (this) { // Lookup in map ILoggerRepository rep = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; if (rep == null) { // Not found, therefore create LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); // Must specify defaults string actualRepositoryName = repositoryName; Type actualRepositoryType = repositoryType; if (readAssemblyAttributes) { // Get the repository and type from the assembly attributes GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); } LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); // Lookup the repository in the map (as this may already be defined) rep = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; if (rep == null) { // Create the repository rep = CreateRepository(actualRepositoryName, actualRepositoryType); if (readAssemblyAttributes) { try { // Look for aliasing attributes LoadAliases(repositoryAssembly, rep); // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); // Configure the repository using the assembly attributes ConfigureRepository(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } else { LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); if (readAssemblyAttributes) { try { // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } m_assembly2repositoryMap[repositoryAssembly] = rep; } return(rep); } }
protected override void Append(LoggingEvent loggingEvent) { LogLog.Debug(declaringType, "Debug - Appending..."); LogLog.Warn(declaringType, "Warn - Appending..."); LogLog.Error(declaringType, "Error - Appending..."); }
/// <summary> /// Gets the repository name and repository type for the specified assembly. /// </summary> /// <param name="assembly">The assembly that has a <see cref="log4net.Config.RepositoryAttribute"/>.</param> /// <param name="repositoryName">in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling.</param> /// <param name="repositoryType">in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly" /> is <see langword="null" />.</exception> private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) { if (assembly == null) { throw new ArgumentNullException("assembly"); } try { LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); } catch { // Ignore exception from debug call } try { // Look for the RepositoryAttribute on the assembly object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); if (repositoryAttributes == null || repositoryAttributes.Length == 0) { // This is not a problem, but its nice to know what is going on. LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); } else { if (repositoryAttributes.Length > 1) { LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); } log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; if (domAttr == null) { LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); } else { // If the Name property is set then override the default if (domAttr.Name != null) { repositoryName = domAttr.Name; } // If the RepositoryType property is set then override the default if (domAttr.RepositoryType != null) { // Check that the type is a repository if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) { repositoryType = domAttr.RepositoryType; } else { LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); } } } } } catch (Exception ex) { LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); } }
protected override void Convert(TextWriter writer, object state) { if (string.IsNullOrEmpty(Option)) { return; } try { var result = string.Empty; const string CMD_LINE = "CommandLine:"; if (Option.StartsWith(CMD_LINE)) { var args = Environment.CommandLine.Split(' '); for (var i = 0; i < args.Length - 1; i++) { if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) { result = args[i + 1]; } } } else { var repo = log4net.LogManager.GetRepository(); if (repo != null) { var realKey = Option; foreach (var key in repo.Properties.GetKeys()) { if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) { realKey = "UNIX:" + Option; } if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) { realKey = "WINDOWS:" + Option; } } var val = repo.Properties[realKey]; if (val is PatternString) { ((PatternString)val).ActivateOptions(); ((PatternString)val).Format(writer); } else if (val != null) { result = val.ToString(); } } } if (!string.IsNullOrEmpty(result)) { result = result.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); writer.Write(result); } } catch (Exception err) { LogLog.Error(GetType(), "Can not convert " + Option, err); } }
/// <summary> /// Hook the shutdown event /// </summary> /// <remarks> /// <para> /// On the full .NET runtime, the static constructor hooks up the /// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events. /// These are used to shutdown the log4net system as the application exits. /// </para> /// </remarks> static LoggerManager() { try { // Register the AppDomain events, note we have to do this with a // method call rather than directly here because the AppDomain // makes a LinkDemand which throws the exception during the JIT phase. RegisterAppDomainEvents(); } catch (System.Security.SecurityException) { LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying " + "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() " + "will not be called automatically when the AppDomain exits. It must be called " + "programmatically."); } // Dump out our assembly version into the log if debug is enabled LogLog.Debug(declaringType, GetVersionInfo()); // Set the default repository selector #if NETCF s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); return; #elif !NETSTANDARD1_3 // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) { // Resolve the config string into a Type Type appRepositorySelectorType = null; try { appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); } catch (Exception ex) { LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type [" + appRepositorySelectorTypeName + "]", ex); } if (appRepositorySelectorType != null) { // Create an instance of the RepositorySelectorType object appRepositorySelectorObj = null; try { appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); } catch (Exception ex) { LogLog.Error(declaringType, "Exception while creating RepositorySelector [" + appRepositorySelectorType.FullName + "]", ex); } if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) { s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; } else { LogLog.Error(declaringType, "RepositorySelector Type [" + appRepositorySelectorType.FullName + "] is not an IRepositorySelector"); } } } #endif // Create the DefaultRepositorySelector if not configured above if (s_repositorySelector == null) { s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); } }
static private void InternalConfigure(ILoggerRepository repository, Uri configUri) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI [" + configUri + "]"); if (configUri == null) { LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); } else { if (configUri.IsFile) { // If URI is local file then call Configure with FileInfo InternalConfigure(repository, new FileInfo(configUri.LocalPath)); } else { // NETCF dose not support WebClient WebRequest configRequest = null; try { configRequest = WebRequest.Create(configUri); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to create WebRequest for URI [" + configUri + "]", ex); } if (configRequest != null) { #if !NETCF_1_0 // authentication may be required, set client to use default credentials try { configRequest.Credentials = CredentialCache.DefaultCredentials; } catch { // ignore security exception } #endif try { #if NETSTANDARD1_3 WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult(); #else WebResponse response = configRequest.GetResponse(); #endif if (response != null) { try { // Open stream on config URI using (Stream configStream = response.GetResponseStream()) { InternalConfigure(repository, configStream); } } finally { response.Close(); } } } catch (Exception ex) { LogLog.Error(declaringType, "Failed to request config from URI [" + configUri + "]", ex); } } } } }
/// <summary> /// Sets a parameter on an object. /// </summary> /// <param name="element">The parameter element.</param> /// <param name="target">The object to set the parameter on.</param> /// <remarks> /// The parameter name must correspond to a writable property /// on the object. The value of the parameter is a string, /// therefore this function will attempt to set a string /// property first. If unable to set a string property it /// will inspect the property and its argument type. It will /// attempt to call a static method called <c>Parse</c> on the /// type of the property. This method will take a single /// string argument and return a value that can be used to /// set the property. /// </remarks> protected void SetParameter(XmlElement element, object target) { // Get the property name string name = element.GetAttribute(NAME_ATTR); // If the name attribute does not exist then use the name of the element if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) { name = element.LocalName; } // Look for the property on the target object Type targetType = target.GetType(); Type propertyType = null; PropertyInfo propInfo = null; MethodInfo methInfo = null; // Try to find a writable property propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); if (propInfo != null && propInfo.CanWrite) { // found a property propertyType = propInfo.PropertyType; } else { propInfo = null; // look for a method with the signature Add<property>(type) methInfo = FindMethodInfo(targetType, name); if (methInfo != null) { propertyType = methInfo.GetParameters()[0].ParameterType; } } if (propertyType == null) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); } else { string propertyValue = null; if (element.GetAttributeNode(VALUE_ATTR) != null) { propertyValue = element.GetAttribute(VALUE_ATTR); } else if (element.HasChildNodes) { // Concatenate the CDATA and Text nodes together foreach (XmlNode childNode in element.ChildNodes) { if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) { if (propertyValue == null) { propertyValue = childNode.InnerText; } else { propertyValue += childNode.InnerText; } } } } if (propertyValue != null) { #if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 try { // Expand environment variables in the string. IDictionary environmentVariables = Environment.GetEnvironmentVariables(); if (HasCaseInsensitiveEnvironment) { environmentVariables = CreateCaseInsensitiveWrapper(environmentVariables); } propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); } catch (System.Security.SecurityException) { // This security exception will occur if the caller does not have // unrestricted environment permission. If this occurs the expansion // will be skipped with the following warning message. LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); } #endif Type parsedObjectConversionTargetType = null; // Check if a specific subtype is specified on the element using the 'type' attribute string subTypeString = element.GetAttribute(TYPE_ATTR); if (subTypeString != null && subTypeString.Length > 0) { // Read the explicit subtype try { #if NETSTANDARD1_3 Type subType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, subTypeString, true, true); #else Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); #endif LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]"); if (!propertyType.IsAssignableFrom(subType)) { // Check if there is an appropriate type converter if (OptionConverter.CanConvertTypeTo(subType, propertyType)) { // Must re-convert to the real property type parsedObjectConversionTargetType = propertyType; // Use sub type as intermediary type propertyType = subType; } else { LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions."); } } else { // The subtype specified is found and is actually a subtype of the property // type, therefore we can switch to using this type. propertyType = subType; } } catch (Exception ex) { LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex); } } // Now try to convert the string value to an acceptable type // to pass to this property. object convertedValue = ConvertStringTo(propertyType, propertyValue); // Check if we need to do an additional conversion if (convertedValue != null && parsedObjectConversionTargetType != null) { LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); } if (convertedValue != null) { if (propInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); try { // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 propInfo.SetValue(target, convertedValue, null); #else propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); #endif } catch (TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); } } else if (methInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); try { // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 methInfo.Invoke(target, new[] { convertedValue }); #else methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture); #endif } catch (TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); } } } else { LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); } } else { object createdObject = null; if (propertyType == typeof(string) && !HasAttributesOrElements(element)) { // If the property is a string and the element is empty (no attributes // or child elements) then we special case the object value to an empty string. // This is necessary because while the String is a class it does not have // a default constructor that creates an empty string, which is the behavior // we are trying to simulate and would be expected from CreateObjectFromXml createdObject = ""; } else { // No value specified Type defaultObjectType = null; if (IsTypeConstructible(propertyType)) { defaultObjectType = propertyType; } createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType); } if (createdObject == null) { LogLog.Error(declaringType, "Failed to create object to set param: " + name); } else { if (propInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]"); try { // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 propInfo.SetValue(target, createdObject, null); #else propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); #endif } catch (TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); } } else if (methInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]"); try { // Pass to the property #if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 methInfo.Invoke(target, new[] { createdObject }); #else methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture); #endif } catch (TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); } } } } } }
static private void InternalConfigure(ILoggerRepository repository, Stream configStream) { LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); if (configStream == null) { LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); } else { // Load the config file into a document XmlDocument doc = new XmlDocument(); try { #if (NETCF) // Create a text reader for the file stream XmlTextReader xmlReader = new XmlTextReader(configStream); #elif NET_2_0 || NETSTANDARD1_3 // Allow the DTD to specify entity includes XmlReaderSettings settings = new XmlReaderSettings(); // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd' // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.' #if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376) settings.DtdProcessing = DtdProcessing.Ignore; #elif !NET_4_0 && !MONO_4_0 settings.ProhibitDtd = false; #else settings.DtdProcessing = DtdProcessing.Parse; #endif // Create a reader over the input stream XmlReader xmlReader = XmlReader.Create(configStream, settings); #else // Create a validating reader around a text reader for the file stream XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream)); // Specify that the reader should not perform validation, but that it should // expand entity refs. xmlReader.ValidationType = ValidationType.None; xmlReader.EntityHandling = EntityHandling.ExpandEntities; #endif // load the data into the document doc.Load(xmlReader); } catch (Exception ex) { LogLog.Error(declaringType, "Error while loading XML configuration", ex); // The document is invalid doc = null; } if (doc != null) { LogLog.Debug(declaringType, "loading XML configuration"); // Configure using the 'log4net' element XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); if (configNodeList.Count == 0) { LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted."); } else if (configNodeList.Count > 1) { LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted."); } else { InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); } } } }
/// <summary> /// Creates an object as specified in XML. /// </summary> /// <param name="element">The XML element that contains the definition of the object.</param> /// <param name="defaultTargetType">The object type to use if not explicitly specified.</param> /// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param> /// <returns>The object or <c>null</c></returns> /// <remarks> /// <para> /// Parse an XML element and create an object instance based on the configuration /// data. /// </para> /// <para> /// The type of the instance may be specified in the XML. If not /// specified then the <paramref name="defaultTargetType"/> is used /// as the type. However the type is specified it must support the /// <paramref name="typeConstraint"/> type. /// </para> /// </remarks> protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) { Type objectType = null; // Get the object type string objectTypeString = element.GetAttribute(TYPE_ATTR); if (objectTypeString == null || objectTypeString.Length == 0) { if (defaultTargetType == null) { LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type."); return(null); } else { // Use the default object type objectType = defaultTargetType; } } else { // Read the explicit object type try { #if NETSTANDARD1_3 objectType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, objectTypeString, true, true); #else objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); #endif } catch (Exception ex) { LogLog.Error(declaringType, "Failed to find type [" + objectTypeString + "]", ex); return(null); } } bool requiresConversion = false; // Got the object type. Check that it meets the typeConstraint if (typeConstraint != null) { if (!typeConstraint.IsAssignableFrom(objectType)) { // Check if there is an appropriate type converter if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) { requiresConversion = true; } else { LogLog.Error(declaringType, "Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions."); return(null); } } } // Create using the default constructor object createdObject = null; try { createdObject = Activator.CreateInstance(objectType); } catch (Exception createInstanceEx) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: " + createInstanceEx.ToString()); } // Set any params on object foreach (XmlNode currentNode in element.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { SetParameter((XmlElement)currentNode, createdObject); } } // Check if we need to call ActivateOptions IOptionHandler optionHandler = createdObject as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } // Ok object should be initialized if (requiresConversion) { // Convert the object type return(OptionConverter.ConvertTypeTo(createdObject, typeConstraint)); } else { // The object is of the correct type return(createdObject); } }
protected IAppender ParseAppender(XmlElement appenderElement) { string attribute = appenderElement.GetAttribute("name"); string typeName = appenderElement.GetAttribute("type"); string[] textArray1 = new string[] { "Loading Appender [", attribute, "] type: [", typeName, "]" }; LogLog.Debug(declaringType, string.Concat(textArray1)); try { IAppender target = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); target.Name = attribute; IEnumerator enumerator = appenderElement.ChildNodes.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlNode current = (XmlNode)enumerator.Current; if (current.NodeType == XmlNodeType.Element) { XmlElement element = (XmlElement)current; if (element.LocalName != "appender-ref") { this.SetParameter(element, target); continue; } string str3 = element.GetAttribute("ref"); IAppenderAttachable attachable = target as IAppenderAttachable; if (attachable == null) { string[] textArray3 = new string[] { "Requesting attachment of appender named [", str3, "] to appender named [", target.Name, "] which does not implement log4net.Core.IAppenderAttachable." }; LogLog.Error(declaringType, string.Concat(textArray3)); continue; } string[] textArray2 = new string[] { "Attaching appender named [", str3, "] to appender named [", target.Name, "]." }; LogLog.Debug(declaringType, string.Concat(textArray2)); IAppender appender2 = this.FindAppenderByReference(element); if (appender2 != null) { attachable.AddAppender(appender2); } } } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } IOptionHandler handler = target as IOptionHandler; if (handler != null) { handler.ActivateOptions(); } LogLog.Debug(declaringType, "Created Appender [" + attribute + "]"); return(target); } catch (Exception exception) { string[] textArray4 = new string[] { "Could not create Appender [", attribute, "] of type [", typeName, "]. Reported error follows." }; LogLog.Error(declaringType, string.Concat(textArray4), exception); return(null); } }