コード例 #1
0
ファイル: LocationInfo.cs プロジェクト: Mariusz11711/DNN
        /// <summary>
        /// Initializes a new instance of the <see cref="LocationInfo"/> class.
        /// Constructor.
        /// </summary>
        /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
        /// the stack boundary into the logging system for this call.</param>
        /// <remarks>
        /// <para>
        /// Initializes a new instance of the <see cref="LocationInfo" />
        /// class based on the current thread.
        /// </para>
        /// </remarks>
        public LocationInfo(Type callerStackBoundaryDeclaringType)
        {
            // Initialize all fields
            this.m_className  = NA;
            this.m_fileName   = NA;
            this.m_lineNumber = NA;
            this.m_methodName = NA;
            this.m_fullInfo   = NA;

#if !(NETCF || NETSTANDARD1_3) // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797
            if (callerStackBoundaryDeclaringType != null)
            {
                try
                {
                    StackTrace st         = new StackTrace(true);
                    int        frameIndex = 0;

                    // skip frames not from fqnOfCallingClass
                    while (frameIndex < st.FrameCount)
                    {
                        StackFrame frame = st.GetFrame(frameIndex);
                        if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType)
                        {
                            break;
                        }

                        frameIndex++;
                    }

                    // skip frames from fqnOfCallingClass
                    while (frameIndex < st.FrameCount)
                    {
                        StackFrame frame = st.GetFrame(frameIndex);
                        if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType)
                        {
                            break;
                        }

                        frameIndex++;
                    }

                    if (frameIndex < st.FrameCount)
                    {
                        // take into account the frames we skip above
                        int       adjustedFrameCount = st.FrameCount - frameIndex;
                        ArrayList stackFramesList    = new ArrayList(adjustedFrameCount);
                        this.m_stackFrames = new StackFrameItem[adjustedFrameCount];
                        for (int i = frameIndex; i < st.FrameCount; i++)
                        {
                            stackFramesList.Add(new StackFrameItem(st.GetFrame(i)));
                        }

                        stackFramesList.CopyTo(this.m_stackFrames, 0);

                        // now frameIndex is the first 'user' caller frame
                        StackFrame locationFrame = st.GetFrame(frameIndex);

                        if (locationFrame != null)
                        {
                            System.Reflection.MethodBase method = locationFrame.GetMethod();

                            if (method != null)
                            {
                                this.m_methodName = method.Name;
                                if (method.DeclaringType != null)
                                {
                                    this.m_className = method.DeclaringType.FullName;
                                }
                            }

                            this.m_fileName   = locationFrame.GetFileName();
                            this.m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);

                            // Combine all location info
                            this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + ':' + this.m_lineNumber + ')';
                        }
                    }
                }
                catch (System.Security.SecurityException)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available.");
                }
            }
#endif
        }
コード例 #2
0
        /// <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="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)_context.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);
            }
        }
コード例 #3
0
 /// <summary>
 /// Creates a new repository selector.
 /// </summary>
 /// <param name="defaultRepositoryType">The type of the repositories to create, must implement <see cref="ILoggerRepository"/></param>
 /// <remarks>
 /// <para>
 /// Create an new repository selector.
 /// The default type for repositories must be specified,
 /// an appropriate value would be <see cref="log4net.Repository.Hierarchy.Hierarchy"/>.
 /// </para>
 /// </remarks>
 /// <exception cref="ArgumentNullException"><paramref name="defaultRepositoryType"/> is <see langword="null" />.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/>.</exception>
 public RepositorySelector(IComponentContext context)
 {
     _context = context;
     LogLog.Debug(declaringType, "defaultRepositoryType [" + m_defaultRepositoryType + "]");
 }
コード例 #4
0
        /// <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
            var 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
            var  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("XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target + "]");
            }
            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)
                {
                    try
                    {
                        // Expand environment variables in the string.
                        propertyValue = OptionConverter.SubstituteVariables(propertyValue, Environment.GetEnvironmentVariables());
                    }
                    catch (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(
                            "XmlHierarchyConfigurator: Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }

                    Type parsedObjectConversionTargetType = null;

                    // Check if a specific subtype is specified on the element using the 'type' attribute
                    var subTypeString = element.GetAttribute(TYPE_ATTR);
                    if (subTypeString != null && subTypeString.Length > 0)
                    {
                        // Read the explicit subtype
                        try
                        {
                            var subType = SystemInfo.GetTypeFromString(subTypeString, true, true);

                            LogLog.Debug("XmlHierarchyConfigurator: 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("XmlHierarchyConfigurator: 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(
                                "XmlHierarchyConfigurator: 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.

                    var convertedValue = ConvertStringTo(propertyType, propertyValue);

                    // Check if we need to do an additional conversion
                    if (convertedValue != null && parsedObjectConversionTargetType != null)
                    {
                        LogLog.Debug("XmlHierarchyConfigurator: 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("XmlHierarchyConfigurator: Setting Property [" + propInfo.Name + "] to " +
                                         convertedValue.GetType().Name + " value [" + convertedValue + "]");

                            try
                            {
                                // Pass to the property
                                propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null,
                                                  CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(
                                    "XmlHierarchyConfigurator: Failed to set parameter [" + propInfo.Name + "] on object [" +
                                    target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                            }
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("XmlHierarchyConfigurator: Setting Collection Property [" + methInfo.Name + "] to " +
                                         convertedValue.GetType().Name + " value [" + convertedValue + "]");

                            try
                            {
                                // Pass to the property
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue },
                                                CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(
                                    "XmlHierarchyConfigurator: Failed to set parameter [" + name + "] on object [" + target +
                                    "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                    else
                    {
                        LogLog.Warn("XmlHierarchyConfigurator: 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("XmlHierarchyConfigurator: Failed to create object to set param: " + name);
                    }
                    else
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("XmlHierarchyConfigurator: Setting Property [" + propInfo.Name + "] to object [" +
                                         createdObject + "]");

                            try
                            {
                                // Pass to the property
                                propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null,
                                                  CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(
                                    "XmlHierarchyConfigurator: Failed to set parameter [" + propInfo.Name + "] on object [" +
                                    target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                            }
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("XmlHierarchyConfigurator: Setting Collection Property [" + methInfo.Name +
                                         "] to object [" + createdObject + "]");

                            try
                            {
                                // Pass to the property
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject },
                                                CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(
                                    "XmlHierarchyConfigurator: Failed to set parameter [" + methInfo.Name + "] on object [" +
                                    target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Initialize the appender based on the options set
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is part of the <see cref="IOptionHandler"/> delayed object
        /// activation scheme. The <see cref="ActivateOptions"/> method must
        /// be called on this object after the configuration properties have
        /// been set. Until <see cref="ActivateOptions"/> is called this
        /// object is in an undefined state and must not be used.
        /// </para>
        /// <para>
        /// If any of the configuration properties are modified then
        /// <see cref="ActivateOptions"/> must be called again.
        /// </para>
        /// </remarks>
        override public void ActivateOptions()
        {
            try
            {
                base.ActivateOptions();

                if (m_securityContext == null)
                {
                    m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
                }

                bool   sourceAlreadyExists = false;
                string currentLogName      = null;

                using (SecurityContext.Impersonate(this))
                {
                    sourceAlreadyExists = EventLog.SourceExists(m_applicationName);
                    if (sourceAlreadyExists)
                    {
                        currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                }

                if (sourceAlreadyExists && currentLogName != m_logName)
                {
                    LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]");
                }
                else if (!sourceAlreadyExists)
                {
                    LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]");
                }

                string registeredLogName = null;

                using (SecurityContext.Impersonate(this))
                {
                    if (sourceAlreadyExists && currentLogName != m_logName)
                    {
                        //
                        // Re-register this to the current application if the user has changed
                        // the application / logfile association
                        //
                        EventLog.DeleteEventSource(m_applicationName, m_machineName);
                        CreateEventSource(m_applicationName, m_logName, m_machineName);

                        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                    else if (!sourceAlreadyExists)
                    {
                        CreateEventSource(m_applicationName, m_logName, m_machineName);

                        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                }

                m_levelMapping.ActivateOptions();

                LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]");
            }
            catch (System.Security.SecurityException ex)
            {
                ErrorHandler.Error("Caught a SecurityException trying to access the EventLog.  Most likely the event source "
                                   + m_applicationName
                                   + " doesn't exist and must be created by a local administrator.  Will disable EventLogAppender."
                                   + "  See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog",
                                   ex);
                Threshold = Level.Off;
            }
        }
コード例 #6
0
        /// <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>
        private 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(declaringType, "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(declaringType, "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(declaringType, "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));
            }
        }
コード例 #7
0
        /// <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
            var objectTypeString = element.GetAttribute(TYPE_ATTR);

            if (objectTypeString == null || objectTypeString.Length == 0)
            {
                if (defaultTargetType == null)
                {
                    LogLog.Error("XmlHierarchyConfigurator: 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
                {
                    objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
                }
                catch (Exception ex)
                {
                    LogLog.Error("XmlHierarchyConfigurator: Failed to find type [" + objectTypeString + "]", ex);
                    return(null);
                }
            }

            var 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("XmlHierarchyConfigurator: 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("XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName +
                             "] Exception: " + createInstanceEx);
            }

            // 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
            var 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);
            }
        }
コード例 #8
0
 private void SendErrorToRaygunInBackground(RaygunMessage raygunMessage)
 {
     LogLog.Debug(DeclaringType, string.Format("RaygunAppender: Sending Raygun message in a background task. Retries: '{0}', TimeBetweenRetries: '{1}'", Retries, TimeBetweenRetries));
     new TaskFactory(_taskScheduler)
     .StartNew(() => SendErrorToRaygun(raygunMessage));
 }
コード例 #9
0
 protected RaygunAppenderBase(IRaygunMessageBuilder raygunMessageBuilder, IRaygunClientFactory raygunClientFactory)
     : this(new UserCustomDataBuilder(), raygunMessageBuilder, raygunClientFactory,
            new TypeActivator(l => LogLog.Debug(DeclaringType, l)), TaskScheduler.Default)
 {
 }
コード例 #10
0
ファイル: Logger.cs プロジェクト: Heather/log4net
        /// <summary>
        /// Deliver the <see cref="LoggingEvent"/> to the attached appenders.
        /// </summary>
        /// <param name="loggingEvent">The event to log.</param>
        /// <remarks>
        /// <para>
        /// Call the appenders in the hierarchy starting at
        /// <c>this</c>. If no appenders could be found, emit a
        /// warning.
        /// </para>
        /// <para>
        /// This method calls all the appenders inherited from the
        /// hierarchy circumventing any evaluation of whether to log or not
        /// to log the particular log request.
        /// </para>
        /// </remarks>
        virtual protected void CallAppenders(LoggingEvent loggingEvent)
        {
            if (loggingEvent == null)
            {
                throw new ArgumentNullException("loggingEvent");
            }

            int writes = 0;

            for (Logger c = this; c != null; c = c.m_parent)
            {
                if (c.m_appenderAttachedImpl != null)
                {
                    // Protected against simultaneous call to addAppender, removeAppender,...
                    c.m_appenderLock.AcquireReaderLock();
                    try
                    {
                        if (c.m_appenderAttachedImpl != null)
                        {
                            writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent);
                        }
                    }
                    finally
                    {
                        c.m_appenderLock.ReleaseReaderLock();
                    }
                }

                if (!c.m_additive)
                {
                    break;
                }
            }

            // No appenders in hierarchy, warn user only once.
            //
            // Note that by including the AppDomain values for the currently running
            // thread, it becomes much easier to see which application the warning
            // is from, which is especially helpful in a multi-AppDomain environment
            // (like IIS with multiple VDIRS).  Without this, it can be difficult
            // or impossible to determine which .config file is missing appender
            // definitions.
            //
            if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0)
            {
                LogLog.Debug(declaringType, "No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]");
                LogLog.Debug(declaringType, "Please initialize the log4net system properly.");
                try
                {
                    LogLog.Debug(declaringType, "    Current AppDomain context information: ");
                    LogLog.Debug(declaringType, "       BaseDirectory   : " + SystemInfo.ApplicationBaseDirectory);
#if !NETCF
                    LogLog.Debug(declaringType, "       FriendlyName    : " + AppDomain.CurrentDomain.FriendlyName);
                    LogLog.Debug(declaringType, "       DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory);
#endif
                }
                catch (System.Security.SecurityException)
                {
                    // Insufficient permissions to display info from the AppDomain
                }
                m_hierarchy.EmittedNoAppenderWarning = true;
            }
        }
コード例 #11
0
		/// <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);
						}
					}
				}
			}
		}
コード例 #12
0
        /// <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;
            }

            string quietModeAttribute = element.GetAttribute(QUIETMODE_ATTR);

            LogLog.Debug(declaringType, QUIETMODE_ATTR + " attribute [" + quietModeAttribute + "].");


            if (quietModeAttribute.Length > 0 && quietModeAttribute != "null")
            {
                LogLog.QuietMode = OptionConverter.ToBoolean(quietModeAttribute, false);
            }
            else
            {
                LogLog.Debug(declaringType, "Ignoring " + QUIETMODE_ATTR + " attribute.");
            }


            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.");
                }
            }


            foreach (XmlNode node in element.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                XmlElement xe = (XmlElement)node;
                if (xe.LocalName == LOGGER_TAG)
                {
                    ParseLogger(xe);
                }
                else if (xe.LocalName == APPENDER_TAG)
                {
                    //....
                }
                else if (xe.LocalName == PLUGINS)
                {
                    ParsePlugins(xe);
                }
                else
                {
                    SetParameter(xe, m_hierarchy);
                }
            }

            //if (rootelementname !=
        }
コード例 #13
0
        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="element"></param>
        /// <param name="target"></param>
        private void SetParameter(XmlElement element, object target)
        {
            string name = element.GetAttribute(NAME_ATTR);

            if (element.LocalName != PARAM_TAG || string.IsNullOrEmpty(name))
            {
                name = element.LocalName;
            }

            Type targetType = target.GetType();

            Type propertyType = null;

            PropertyInfo propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
            MethodInfo   methInfo = null;

            if (propInfo != null && propInfo.CanWrite)
            {
                propertyType = propInfo.PropertyType;
            }
            else
            {
                propInfo = null;
                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() + "]");
                return;
            }


            string propvalue = null;

            if (element.GetAttributeNode(VALUE_ATTR) != null)
            {
                propvalue = element.GetAttribute(VALUE_ATTR);
            }


            if (propvalue != null)
            {
                object convertedValue = ConvertStringTo(propertyType, propvalue);

                try
                {
                    // Pass to the property
                    propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                }
                catch (TargetInvocationException targetInvocationEx)
                {
                    LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                }
            }
            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
                            propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        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
                            methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture);
                        }
                        catch (TargetInvocationException targetInvocationEx)
                        {
                            LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                        }
                    }
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Prepares the database command and initialize the parameters.
        /// </summary>
        private void InitializeDatabaseCommand()
        {
            if (m_dbConnection != null && m_usePreparedCommand)
            {
                try
                {
                    // Cleanup any existing command or connection
                    if (m_dbCommand != null)
                    {
                        try
                        {
                            m_dbCommand.Dispose();
                        }
                        catch (Exception ex)
                        {
                            LogLog.Warn("AdoNetAppender: Exception while disposing cached command object", ex);
                        }
                        m_dbCommand = null;
                    }

                    // Create the command object
                    m_dbCommand = m_dbConnection.CreateCommand();

                    // Set the command string
                    m_dbCommand.CommandText = m_commandText;

                    // Set the command type
                    m_dbCommand.CommandType = m_commandType;
                }
                catch (System.Exception e)
                {
                    ErrorHandler.Error("Could not create database command [" + m_commandText + "]", e);

                    if (m_dbCommand != null)
                    {
                        try
                        {
                            m_dbCommand.Dispose();
                        }
                        catch
                        {
                            // Ignore exception
                        }
                        m_dbCommand = null;
                    }
                }

                if (m_dbCommand != null)
                {
                    try
                    {
                        foreach (AdoNetAppenderParameter param in m_parameters)
                        {
                            try
                            {
                                param.Prepare(m_dbCommand);
                            }
                            catch (System.Exception e)
                            {
                                ErrorHandler.Error("Could not add database command parameter [" + param.ParameterName + "]", e);
                                throw;
                            }
                        }
                    }
                    catch
                    {
                        try
                        {
                            m_dbCommand.Dispose();
                        }
                        catch
                        {
                            // Ignore exception
                        }
                        m_dbCommand = null;
                    }
                }

                if (m_dbCommand != null)
                {
                    try
                    {
                        // Prepare the command statement.
                        m_dbCommand.Prepare();
                    }
                    catch (System.Exception e)
                    {
                        ErrorHandler.Error("Could not prepare database command [" + m_commandText + "]", e);
                        try
                        {
                            m_dbCommand.Dispose();
                        }
                        catch
                        {
                            // Ignore exception
                        }
                        m_dbCommand = null;
                    }
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Writes the events to the database using the transaction specified.
        /// </summary>
        /// <param name="dbTran">The transaction that the events will be executed under.</param>
        /// <param name="events">The array of events to insert into the database.</param>
        /// <remarks>
        /// <para>
        /// The transaction argument can be <c>null</c> if the appender has been
        /// configured not to use transactions. See <see cref="UseTransactions"/>
        /// property for more information.
        /// </para>
        /// </remarks>
        virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
        {
            // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks
            if (CommandText != null && CommandText.Trim() != "")
            {
                using (IDbCommand dbCmd = Connection.CreateCommand())
                {
                    // Set the command string
                    dbCmd.CommandText = CommandText;

                    // Set the command type
                    dbCmd.CommandType = CommandType;

                    // Send buffer using the prepared command object
                    if (dbTran != null)
                    {
                        dbCmd.Transaction = dbTran;
                    }

                    // clear parameters that have been set
                    dbCmd.Parameters.Clear();

                    // Add the query parameters
                    foreach (AdoNetAppenderParameter param in m_parameters)
                    {
                        param.Prepare(dbCmd);
                    }

                    // prepare the command, which is significantly faster
                    dbCmd.Prepare();

                    // run for all events
                    foreach (LoggingEvent e in events)
                    {
                        // Set the parameter values
                        foreach (AdoNetAppenderParameter param in m_parameters)
                        {
                            param.FormatValue(dbCmd, e);
                        }

                        // Execute the query
                        dbCmd.ExecuteNonQuery();
                    }
                }
            }
            else
            {
                // create a new command
                using (IDbCommand dbCmd = Connection.CreateCommand())
                {
                    if (dbTran != null)
                    {
                        dbCmd.Transaction = dbTran;
                    }
                    // run for all events
                    foreach (LoggingEvent e in events)
                    {
                        // Get the command text from the Layout
                        string logStatement = GetLogStatement(e);

                        LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]");

                        dbCmd.CommandText = logStatement;
                        dbCmd.ExecuteNonQuery();
                    }
                }
            }
        }
コード例 #16
0
        /// <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 || UNITY_WEBPLAYER
            s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
#else
            // 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");
                    }
                }
            }

            // Create the DefaultRepositorySelector if not configured above
            if (s_repositorySelector == null)
            {
                s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
            }
#endif
        }
コード例 #17
0
ファイル: KafkaLog.cs プロジェクト: ztxyzu/MasterChief
 /// <summary>
 ///     Warns the format.
 /// </summary>
 /// <param name="format">The format.</param>
 /// <param name="args">The arguments.</param>
 public void WarnFormat(string format, params object[] args)
 {
     LogLog.Debug(GetType(), string.Format(format, args));
 }
コード例 #18
0
        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
                        {
                            WebResponse response = configRequest.GetResponse();
                            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);
                        }
                    }
                }
            }
        }
コード例 #19
0
        /// <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)
        {
            // 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(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex);
                    }

                    if (systemConfigFilePath != null)
                    {
                        Uri 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(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex);
                    }

                    if (systemConfigFilePath != null)
                    {
                        UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath));

                        // Remove the current extension from the systemConfigFileUri path
                        string path             = builder.Path;
                        int    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(declaringType, "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(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI");
                    }
                    XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile);
                }
            }
        }
コード例 #20
0
        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 || UNITY_4_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 !NET_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);
                    }
                }
            }
        }
コード例 #21
0
        /// <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)
        {
            var appenderName = appenderElement.GetAttribute(NAME_ATTR);
            var typeName     = appenderElement.GetAttribute(TYPE_ATTR);

            LogLog.Debug("XmlHierarchyConfigurator: Loading Appender [" + appenderName + "] type: [" + typeName + "]");
            try
            {
                var appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true));
                appender.Name = appenderName;

                foreach (XmlNode currentNode in appenderElement.ChildNodes)
                {
                    /* We're only interested in Elements */
                    if (currentNode.NodeType == XmlNodeType.Element)
                    {
                        var currentElement = (XmlElement)currentNode;

                        // Look for the appender ref tag
                        if (currentElement.LocalName == APPENDER_REF_TAG)
                        {
                            var refName = currentElement.GetAttribute(REF_ATTR);

                            var appenderContainer = appender as IAppenderAttachable;
                            if (appenderContainer != null)
                            {
                                LogLog.Debug("XmlHierarchyConfigurator: Attaching appender named [" + refName +
                                             "] to appender named [" + appender.Name + "].");

                                var referencedAppender = FindAppenderByReference(currentElement);
                                if (referencedAppender != null)
                                {
                                    appenderContainer.AddAppender(referencedAppender);
                                }
                            }
                            else
                            {
                                LogLog.Error("XmlHierarchyConfigurator: 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);
                        }
                    }
                }

                var optionHandler = appender as IOptionHandler;
                if (optionHandler != null)
                {
                    optionHandler.ActivateOptions();
                }

                LogLog.Debug("XmlHierarchyConfigurator: 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(
                    "XmlHierarchyConfigurator: Could not create Appender [" + appenderName + "] of type [" + typeName +
                    "]. Reported error follows.", ex);
                return(null);
            }
        }
コード例 #22
0
 private void FlushLog(object sender, ElapsedEventArgs e)
 {
     LogLog.Debug(GetType(), "Flushing logs");
     Flush();
 }
コード例 #23
0
        /// <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;
            }

            var rootElementName = element.LocalName;

            if (rootElementName != CONFIGURATION_TAG)
            {
                LogLog.Error("XmlHierarchyConfigurator: Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
                return;
            }

            if (!LogLog.InternalDebugging)
            {
                // Look for a debug attribute to enable internal debug
                var debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
                LogLog.Debug("XmlHierarchyConfigurator: " + INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "].");

                if (debugAttribute.Length > 0 && debugAttribute != "null")
                {
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
                }
                else
                {
                    LogLog.Debug("XmlHierarchyConfigurator: Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
                }

                var confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR);
                if (confDebug.Length > 0 && confDebug != "null")
                {
                    LogLog.Warn("XmlHierarchyConfigurator: The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated.");
                    LogLog.Warn("XmlHierarchyConfigurator: Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead.");
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true);
                }
            }

            // Default mode is merge
            var configUpdateMode = ConfigUpdateMode.Merge;

            // Look for the config update attribute
            var 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("XmlHierarchyConfigurator: Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" +
                                 configUpdateModeAttribute + "]");
                }
            }

            // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0
            LogLog.Debug("XmlHierarchyConfigurator: Configuration update mode [" + configUpdateMode + "].");

            // Only reset configuration if overwrite flag specified
            if (configUpdateMode == ConfigUpdateMode.Overwrite)
            {
                // Reset to original unset configuration
                m_hierarchy.ResetConfiguration();
                LogLog.Debug("XmlHierarchyConfigurator: 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)
                {
                    var 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
            var thresholdStr = element.GetAttribute(THRESHOLD_ATTR);

            LogLog.Debug("XmlHierarchyConfigurator: Hierarchy Threshold [" + thresholdStr + "]");
            if (thresholdStr.Length > 0 && thresholdStr != "null")
            {
                var thresholdLevel = (Level)ConvertStringTo(typeof(Level), thresholdStr);
                if (thresholdLevel != null)
                {
                    m_hierarchy.Threshold = thresholdLevel;
                }
                else
                {
                    LogLog.Warn("XmlHierarchyConfigurator: Unable to set hierarchy threshold using value [" + thresholdStr +
                                "] (with acceptable conversion types)");
                }
            }

            // Done reading config
        }
コード例 #24
0
        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;
                            }
                        }
                    }
                }
            }
        }
コード例 #25
0
        /// <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="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);
            }
        }
コード例 #26
0
        private void SetupClient(ClientConfig clientConfig)
        {
            if (Client != null)
            {
                return;
            }

            if (clientConfig == null)
            {
                clientConfig = (TConfig)Activator.CreateInstance(typeof(TConfig));
            }


            if (string.IsNullOrEmpty(_endPoint) && clientConfig.RegionEndpoint == null && ConfigurationManager.AppSettings["AWSServiceEndpoint"] != null)
            {
                _endPoint = ConfigurationManager.AppSettings["AWSServiceEndpoint"];
            }

            if (string.IsNullOrEmpty(_accessKey) && ConfigurationManager.AppSettings["AWSAccessKey"] != null)
            {
                _accessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
            }

            if (string.IsNullOrEmpty(_secret) && ConfigurationManager.AppSettings["AWSSecretKey"] != null)
            {
                _secret = ConfigurationManager.AppSettings["AWSSecretKey"];
            }

            if (!string.IsNullOrEmpty(_endPoint))
            {
                if (_endPoint.StartsWith("http"))
                {
                    clientConfig.ServiceURL = _endPoint;
                }
                else
                {
                    clientConfig.RegionEndpoint = RegionEndpoint.GetBySystemName(_endPoint);
                }
            }

            if (string.IsNullOrEmpty(_accessKey))
            {
                try
                {
                    if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AWSProfileName"]) || ProfileManager.ListProfileNames().Contains("default"))
                    {
                        if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AWSRegion"]))
                        {
                            Client = (TClient)AWSClientFactoryWrapper <TClient> .CreateServiceClient();
                        }
                        else if (clientConfig.RegionEndpoint != null || clientConfig.ServiceURL != null)
                        {
                            Client = (TClient)AWSClientFactoryWrapper <TClient> .CreateServiceClient(clientConfig);
                        }
                    }
                    else
                    {
                        foreach (var availableRole in InstanceProfileAWSCredentials.GetAvailableRoles())
                        {
                            LogLog.Debug(typeof(ClientWrapperBase <,>), "Role: " + availableRole);
                        }
                        Client = (TClient)AWSClientFactoryWrapper <TClient> .CreateServiceClient(clientConfig);
                    }
                }
                catch (AmazonServiceException e)
                {
                    LogLog.Debug(typeof(ClientWrapperBase <,>), "Exception caught while creating client", e);
                }
            }
コード例 #27
0
        /// <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);
            }
        }
コード例 #28
0
        /// <summary>
        /// Writes the events to the database using the transaction specified.
        /// </summary>
        /// <param name="dbTran">The transaction that the events will be executed under.</param>
        /// <param name="events">The array of events to insert into the database.</param>
        /// <remarks>
        /// <para>
        /// The transaction argument can be <c>null</c> if the appender has been
        /// configured not to use transactions. See <see cref="UseTransactions"/>
        /// property for more information.
        /// </para>
        /// </remarks>
        protected virtual void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
        {
            // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks
            if (CommandText != null && CommandText.Trim() != "")
            {
                using (IDbCommand dbCmd = Connection.CreateCommand())
                {
                    // Set the command string
                    dbCmd.CommandText = CommandText;

                    // Set the command type
                    dbCmd.CommandType = CommandType;
                    // Send buffer using the prepared command object
                    if (dbTran != null)
                    {
                        dbCmd.Transaction = dbTran;
                    }

                    try
                    {
                        // prepare the command, which is significantly faster
                        Prepare(dbCmd);
                    }
                    catch (Exception)
                    {
                        if (dbTran != null)
                        {
                            // rethrow exception in transaction mode, cuz now transaction is in failed state
                            throw;
                        }

                        // ignore prepare exceptions as they can happen without affecting actual logging, eg on npgsql
                    }

                    // run for all events
                    foreach (LoggingEvent e in events)
                    {
                        // No need to clear dbCmd.Parameters, just use existing.
                        // Set the parameter values
                        foreach (AdoNetAppenderParameter param in m_parameters)
                        {
                            param.FormatValue(dbCmd, e);
                        }

                        // Execute the query
                        dbCmd.ExecuteNonQuery();
                    }
                }
            }
            else
            {
                // create a new command
                using (IDbCommand dbCmd = Connection.CreateCommand())
                {
                    if (dbTran != null)
                    {
                        dbCmd.Transaction = dbTran;
                    }
                    // run for all events
                    foreach (LoggingEvent e in events)
                    {
                        // Get the command text from the Layout
                        string logStatement = GetLogStatement(e);

                        LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]");

                        dbCmd.CommandText = logStatement;
                        dbCmd.ExecuteNonQuery();
                    }
                }
            }
        }
コード例 #29
0
        /// <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
                    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 + "]");

                            throw new NotImplementedException();
                            //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
                                throw new NotImplementedException();
                                //XmlConfigurator.Configure(repository, repositoryConfigUri);
                            }
                            catch (Exception ex)
                            {
                                LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex);
                            }
                        }
                    }
                }
            }
        }
コード例 #30
0
        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 = 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);
            }
        }