private AmazonWebServiceResponse PutLogEvents(PutLogEventsRequest putLogEventsRequest)
        {
            if (!_validatedGroupNames.ContainsKey(putLogEventsRequest.LogGroupName) || !_validatedStreamNames.ContainsKey(putLogEventsRequest.LogStreamName))
            {
                lock (_lockObject)
                {
                    if (!_validatedGroupNames.ContainsKey(putLogEventsRequest.LogGroupName))
                    {
                        try
                        {
                            Client.CreateLogGroup(new CreateLogGroupRequest {
                                LogGroupName = putLogEventsRequest.LogGroupName
                            });
                        }
                        catch (ResourceAlreadyExistsException)
                        {
                        }
                        _validatedGroupNames.TryAdd(putLogEventsRequest.LogGroupName, putLogEventsRequest.LogGroupName);
                    }

                    if (!_validatedStreamNames.ContainsKey(putLogEventsRequest.LogStreamName))
                    {
                        try
                        {
                            Client.CreateLogStream(new CreateLogStreamRequest {
                                LogGroupName = putLogEventsRequest.LogGroupName, LogStreamName = putLogEventsRequest.LogStreamName
                            });
                        }
                        catch (ResourceAlreadyExistsException)
                        {
                        }
                        _validatedStreamNames.TryAdd(putLogEventsRequest.LogStreamName, putLogEventsRequest.LogStreamName);
                    }
                }
            }

            lock (_lockObject)
            {
                AmazonWebServiceResponse ret = null;

                string nextSequenceToken;
                var    key = putLogEventsRequest.LogGroupName + "/" + putLogEventsRequest.LogStreamName;
                if (!_nextSequenceToken.ContainsKey(key))
                {
                    _nextSequenceToken[key] = null;
                }
                nextSequenceToken = _nextSequenceToken[key];

                for (var i = 0; i < 10 && ret == null; i++)
                {
                    try
                    {
                        try
                        {
                            putLogEventsRequest.SequenceToken = nextSequenceToken;
                            var putLogEventsResponse = Client.PutLogEvents(putLogEventsRequest);
                            _nextSequenceToken[key] = putLogEventsResponse.NextSequenceToken;
                            ret = putLogEventsResponse;
                        }
                        catch (ResourceNotFoundException)
                        {
                            throw;
                        }
                    }
                    catch (DataAlreadyAcceptedException e)
                    {
                        var matchCollection = Regex.Matches(e.Message, @"[0-9]{20,}");
                        if (matchCollection.Count > 0)
                        {
                            nextSequenceToken = matchCollection[0].Value;
                        }
                        else
                        {
                            nextSequenceToken = null;
                        }
                    }
                    catch (InvalidSequenceTokenException e)
                    {
                        var matchCollection = Regex.Matches(e.Message, @"[0-9]{20,}");
                        if (matchCollection.Count > 0)
                        {
                            nextSequenceToken = matchCollection[0].Value;
                        }
                        else
                        {
                            nextSequenceToken = null;
                        }
                    }
                    catch (OperationAbortedException)
                    {
                        LogLog.Debug(typeof(CloudWatchLogsClientWrapper), "Task lost due to conflicting operation");
                    }
                }
                return(ret);
            }
        }
Exemplo n.º 2
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);
                }
            }
Exemplo n.º 3
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();
                    }
                }
            }
        }
 private void FlushLog(object sender, ElapsedEventArgs e)
 {
     LogLog.Debug(GetType(), "Flushing logs");
     Flush();
 }
        /// <summary>
        /// Sets a parameter on an object.
        /// </summary>
        /// <param name="element">The parameter element.</param>
        /// <param name="target">The object to set the parameter on.</param>
        /// <remarks>
        /// The parameter name must correspond to a writable property
        /// on the object. The value of the parameter is a string,
        /// therefore this function will attempt to set a string
        /// property first. If unable to set a string property it
        /// will inspect the property and its argument type. It will
        /// attempt to call a static method called <c>Parse</c> on the
        /// type of the property. This method will take a single
        /// string argument and return a value that can be used to
        /// set the property.
        /// </remarks>
        protected void SetParameter(XmlElement element, object target)
        {
            // Get the property name
            string name = element.GetAttribute(NAME_ATTR);

            // If the name attribute does not exist then use the name of the element
            if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
            {
                name = element.LocalName;
            }

            // Look for the property on the target object
            Type targetType   = target.GetType();
            Type propertyType = null;

            PropertyInfo propInfo = null;
            MethodInfo   methInfo = null;

            // Try to find a writable property
            propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
            if (propInfo != null && propInfo.CanWrite)
            {
                // found a property
                propertyType = propInfo.PropertyType;
            }
            else
            {
                propInfo = null;

                // look for a method with the signature Add<property>(type)
                methInfo = this.FindMethodInfo(targetType, name);

                if (methInfo != null)
                {
                    propertyType = methInfo.GetParameters()[0].ParameterType;
                }
            }

            if (propertyType == null)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
            }
            else
            {
                string propertyValue = null;

                if (element.GetAttributeNode(VALUE_ATTR) != null)
                {
                    propertyValue = element.GetAttribute(VALUE_ATTR);
                }
                else if (element.HasChildNodes)
                {
                    // Concatenate the CDATA and Text nodes together
                    foreach (XmlNode childNode in element.ChildNodes)
                    {
                        if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
                        {
                            if (propertyValue == null)
                            {
                                propertyValue = childNode.InnerText;
                            }
                            else
                            {
                                propertyValue += childNode.InnerText;
                            }
                        }
                    }
                }

                if (propertyValue != null)
                {
#if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6
                    try
                    {
                        // Expand environment variables in the string.
                        IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                        if (this.HasCaseInsensitiveEnvironment)
                        {
                            environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables);
                        }

                        propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables);
                    }
                    catch (System.Security.SecurityException)
                    {
                        // This security exception will occur if the caller does not have
                        // unrestricted environment permission. If this occurs the expansion
                        // will be skipped with the following warning message.
                        LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }
#endif

                    Type parsedObjectConversionTargetType = null;

                    // Check if a specific subtype is specified on the element using the 'type' attribute
                    string subTypeString = element.GetAttribute(TYPE_ATTR);
                    if (subTypeString != null && subTypeString.Length > 0)
                    {
                        // Read the explicit subtype
                        try
                        {
#if NETSTANDARD1_3
                            Type subType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, subTypeString, true, true);
#else
                            Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);
#endif

                            LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]");

                            if (!propertyType.IsAssignableFrom(subType))
                            {
                                // Check if there is an appropriate type converter
                                if (OptionConverter.CanConvertTypeTo(subType, propertyType))
                                {
                                    // Must re-convert to the real property type
                                    parsedObjectConversionTargetType = propertyType;

                                    // Use sub type as intermediary type
                                    propertyType = subType;
                                }
                                else
                                {
                                    LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions.");
                                }
                            }
                            else
                            {
                                // The subtype specified is found and is actually a subtype of the property
                                // type, therefore we can switch to using this type.
                                propertyType = subType;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex);
                        }
                    }

                    // Now try to convert the string value to an acceptable type
                    // to pass to this property.
                    object convertedValue = this.ConvertStringTo(propertyType, propertyValue);

                    // Check if we need to do an additional conversion
                    if (convertedValue != null && parsedObjectConversionTargetType != null)
                    {
                        LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]");
                        convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType);
                    }

                    if (convertedValue != null)
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

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

                            try
                            {
                                // Pass to the property
#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5
                                methInfo.Invoke(target, new[] { convertedValue });
#else
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture);
#endif
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                    else
                    {
                        LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
                    }
                }
                else
                {
                    object createdObject = null;

                    if (propertyType == typeof(string) && !this.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 = string.Empty;
                    }
                    else
                    {
                        // No value specified
                        Type defaultObjectType = null;
                        if (IsTypeConstructible(propertyType))
                        {
                            defaultObjectType = propertyType;
                        }

                        createdObject = this.CreateObjectFromXml(element, defaultObjectType, propertyType);
                    }

                    if (createdObject == null)
                    {
                        LogLog.Error(declaringType, "Failed to create object to set param: " + name);
                    }
                    else
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]");

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

                            try
                            {
                                // Pass to the property
#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5
                                methInfo.Invoke(target, new[] { createdObject });
#else
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture);
#endif
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
 protected RaygunAppenderBase(IRaygunMessageBuilder raygunMessageBuilder, IRaygunClientFactory raygunClientFactory)
     : this(new UserCustomDataBuilder(), raygunMessageBuilder, raygunClientFactory,
            new TypeActivator(l => LogLog.Debug(DeclaringType, l)), TaskScheduler.Default)
 {
 }
Exemplo n.º 7
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);
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <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
        }
        /// <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);
                        }
                    }
                }
            }
        }
 protected override void Append(LoggingEvent loggingEvent)
 {
     LogLog.Debug(declaringType, "Debug - Appending...");
     LogLog.Warn(declaringType, "Warn - Appending...");
     LogLog.Error(declaringType, "Error - Appending...");
 }
        /// <summary>
        /// Sets a paramater on an object.
        /// </summary>
        /// <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 'Parse' 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>
        /// <param name="element">The parameter element.</param>
        /// <param name="target">The object to set the parameter on.</param>
        protected void SetParameter(XmlElement element, object target)
        {
            // Get the property name
            string name = element.GetAttribute(NAME_ATTR);

            // If the name attribute does not exist then use the name of the element
            if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
            {
                name = element.LocalName;
            }

            // Look for the property on the target object
            Type targetType   = target.GetType();
            Type propertyType = null;

            PropertyInfo propInfo = null;
            MethodInfo   methInfo = null;

            // Try to find a writable property
            propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.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 = targetType.GetMethod("Add" + name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (methInfo != null && methInfo.IsPublic && !methInfo.IsStatic)
                {
                    System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters();
                    if (methParams.Length == 1)
                    {
                        propertyType = methParams[0].ParameterType;
                    }
                    else
                    {
                        methInfo = null;
                    }
                }
                else
                {
                    methInfo = null;
                }
            }

            if (propertyType == null)
            {
                LogLog.Error("DOMConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
            }
            else
            {
                if (element.GetAttributeNode(VALUE_ATTR) != null)
                {
                    string propertyValue = element.GetAttribute(VALUE_ATTR);

                    // Fixup embedded non-printable chars
                    propertyValue = OptionConverter.ConvertSpecialChars(propertyValue);

#if !NETCF
                    try
                    {
                        // Expand environment variables in the string.
                        propertyValue = OptionConverter.SubstVars(propertyValue, Environment.GetEnvironmentVariables());
                    }
                    catch (System.Security.SecurityException)
                    {
                        // This security exception will occur if the caller does not have
                        // unrestricted environment permission. If this occurs the expansion
                        // will be skipped with the following warning message.
                        LogLog.Debug("DOMConfigurator: Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }
#endif
                    // Now try to convert the string value to an acceptable type
                    // to pass to this property.

                    object convertedValue = ConvertStringTo(propertyType, propertyValue);
                    if (convertedValue != null)
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            // Pass to the property
                            propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            // Pass to the property
                            methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture);
                        }
                    }
                    else
                    {
                        LogLog.Warn("DOMConfigurator: Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
                    }
                }
                else
                {
                    // No value specified
                    Type defaultObjectType = null;
                    if (propertyType.IsClass && !propertyType.IsAbstract)
                    {
                        defaultObjectType = propertyType;
                    }

                    object createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);

                    if (createdObject == null)
                    {
                        LogLog.Error("DOMConfigurator: Failed to create object to set param: " + name);
                    }
                    else
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]");

                            // Pass to the property
                            propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]");

                            // Pass to the property
                            methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture);
                        }
                    }
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Inserts the events into the database.
        /// </summary>
        /// <param name="events">The events to insert into the database.</param>
        /// <remarks>
        /// <para>
        /// Insert all the events specified in the <paramref name="events"/>
        /// array into the database.
        /// </para>
        /// </remarks>
        override protected void SendBuffer(LoggingEvent[] events)
        {
            LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_START");
            if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open))
            {
                LogLog.Debug(typeof(OracleAppender), "OracleAppender: Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection == null) ? "<null>" : m_dbConnection.State.ToString()));
                //LogLog.Debug("OracleAppender: Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection == null) ? "<null>" : m_dbConnection.State.ToString()));

                InitializeDatabaseConnection();
                InitializeDatabaseCommand();
            }

            // Check that the connection exists and is open
            if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open)
            {
                if (m_useTransactions)
                {
                    // Create transaction
                    // NJC - Do this on 2 lines because it can confuse the debugger
                    LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_START_TRANSACTION");
                    OracleTransaction dbTran = null;
                    try
                    {
                        dbTran = m_dbConnection.BeginTransaction();

                        SendBuffer(dbTran, events);

                        // commit transaction
                        dbTran.Commit();
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_END_TRANSACTION");
                    }
                    catch (Exception ex)
                    {
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_TRANSACTION_ERROR:" + ex.Message);
                        // rollback the transaction
                        if (dbTran != null)
                        {
                            try
                            {
                                dbTran.Rollback();
                            }
                            catch (Exception)
                            {
                                // Ignore exception
                            }
                        }

                        // Can't insert into the database. That's a bad thing
                        ErrorHandler.Error("Exception while writing to database", ex);
                    }
                }
                else
                {
                    /*
                     * try catch aggiunto per risolvere problema
                     * mancata riconnessione a Oracle
                     * in caso di blocco comunicazione client/server
                     * (il pool di connessioni è invalido
                     * ma con lo state che rimane segnato a open)
                     * nota:
                     * m_reconnectOnError deve essere configurato a true
                     */
                    try
                    {
                        // Send without transaction
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_NO_TRANSACTION");
                        SendBuffer(null, events);
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_NO_TRANSACTION_DONE");
                    }
                    catch (OracleException exx)
                    {
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_NO_TRANSACTION_ERROR:" + exx.Message);
                        m_dbConnection = null;
                    }
                    catch (Exception exx1)
                    {
                        LogLog.Debug(typeof(OracleAppender), "WRITE_LOG_TO_DB_NO_TRANSACTION_ERROR:" + exx1.Message);
                        m_dbConnection = null;
                        throw;
                    }
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Configures the repository using information from the assembly.
        /// </summary>
        /// <param name="assembly">The assembly containing <see cref="T:log4net.Config.ConfiguratorAttribute" />
        /// attributes which define the configuration for the repository.</param>
        /// <param name="repository">The repository to configure.</param>
        /// <exception cref="T:System.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 ((object)assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }
            object[] array = assembly.GetCustomAttributes(typeof(ConfiguratorAttribute)).ToArray();
            if (array != null && array.Length != 0)
            {
                Array.Sort(array);
                object[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    ConfiguratorAttribute configuratorAttribute = (ConfiguratorAttribute)array2[i];
                    if (configuratorAttribute != null)
                    {
                        try
                        {
                            configuratorAttribute.Configure(assembly, repository);
                        }
                        catch (Exception exception)
                        {
                            LogLog.Error(declaringType, "Exception calling [" + configuratorAttribute.GetType().FullName + "] .Configure method.", exception);
                        }
                    }
                }
            }
            if (!(repository.Name == "log4net-default-repository"))
            {
                return;
            }
            string appSetting = SystemInfo.GetAppSetting("log4net.Config");

            if (appSetting == null || appSetting.Length <= 0)
            {
                return;
            }
            string text = null;

            try
            {
                text = SystemInfo.ApplicationBaseDirectory;
            }
            catch (Exception exception2)
            {
                LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + appSetting + "] will be treated as an absolute URI", exception2);
            }
            string text2 = appSetting;

            if (text != null)
            {
                text2 = Path.Combine(text, appSetting);
            }
            bool result = false;

            bool.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out result);
            if (result)
            {
                FileInfo configFile = null;
                try
                {
                    configFile = new FileInfo(text2);
                }
                catch (Exception exception3)
                {
                    LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + text2 + "]", exception3);
                }
                try
                {
                    LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + text2 + "]");
                    XmlConfigurator.ConfigureAndWatch(repository, configFile);
                }
                catch (Exception exception4)
                {
                    LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + text2 + "]", exception4);
                }
                return;
            }
            Uri uri = null;

            try
            {
                uri = new Uri(text2);
            }
            catch (Exception exception5)
            {
                LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + appSetting + "]", exception5);
            }
            if (uri != null)
            {
                LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + uri.ToString() + "]");
                try
                {
                    XmlConfigurator.Configure(repository, uri);
                }
                catch (Exception exception6)
                {
                    LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + uri + "]", exception6);
                }
            }
        }
Exemplo n.º 14
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="T:log4net.Repository.ILoggerRepository" />.</param>
 /// <param name="repositoryType">The type of repository to create, must implement <see cref="T:log4net.Repository.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="T:log4net.Repository.ILoggerRepository" /> created will be associated with the repository
 /// specified such that a call to <see cref="M:GetRepository(Assembly)" /> with the
 /// same assembly specified will return the same repository instance.
 /// </para>
 /// <para>
 /// The type of the <see cref="T:log4net.Repository.ILoggerRepository" /> created and
 /// the repository to create can be overridden by specifying the
 /// <see cref="T:log4net.Config.RepositoryAttribute" /> attribute on the
 /// <paramref name="repositoryAssembly" />.  The default values are to use the
 /// <paramref name="repositoryType" /> implementation of the
 /// <see cref="T:log4net.Repository.ILoggerRepository" /> interface and to use the
 /// <see cref="P:System.Reflection.AssemblyName.Name" /> as the name of the repository.
 /// </para>
 /// <para>
 /// The <see cref="T:log4net.Repository.ILoggerRepository" /> created will be automatically
 /// configured using any <see cref="T: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="T:log4net.Config.RepositoryAttribute" /> attribute on the
 /// assembly may be used to override the repository type specified in
 /// <paramref name="repositoryType" />.
 /// </para>
 /// </remarks>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="repositoryAssembly" /> is <see langword="null" />.</exception>
 public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes)
 {
     if ((object)repositoryAssembly == null)
     {
         throw new ArgumentNullException("repositoryAssembly");
     }
     if ((object)repositoryType == null)
     {
         repositoryType = m_defaultRepositoryType;
     }
     lock (this)
     {
         ILoggerRepository loggerRepository = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository;
         if (loggerRepository == null)
         {
             LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]");
             string repositoryName2 = repositoryName;
             Type   repositoryType2 = repositoryType;
             if (readAssemblyAttributes)
             {
                 GetInfoForAssembly(repositoryAssembly, ref repositoryName2, ref repositoryType2);
             }
             LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + repositoryName2 + "] and repository type [" + repositoryType2 + "]");
             loggerRepository = (m_name2repositoryMap[repositoryName2] as ILoggerRepository);
             if (loggerRepository == null)
             {
                 loggerRepository = CreateRepository(repositoryName2, repositoryType2);
                 if (readAssemblyAttributes)
                 {
                     try
                     {
                         LoadAliases(repositoryAssembly, loggerRepository);
                         LoadPlugins(repositoryAssembly, loggerRepository);
                         ConfigureRepository(repositoryAssembly, loggerRepository);
                     }
                     catch (Exception exception)
                     {
                         LogLog.Error(declaringType, "Failed to configure repository [" + repositoryName2 + "] from assembly attributes.", exception);
                     }
                 }
             }
             else
             {
                 LogLog.Debug(declaringType, "repository [" + repositoryName2 + "] already exists, using repository type [" + loggerRepository.GetType().FullName + "]");
                 if (readAssemblyAttributes)
                 {
                     try
                     {
                         LoadPlugins(repositoryAssembly, loggerRepository);
                     }
                     catch (Exception exception2)
                     {
                         LogLog.Error(declaringType, "Failed to configure repository [" + repositoryName2 + "] from assembly attributes.", exception2);
                     }
                 }
             }
             m_assembly2repositoryMap[repositoryAssembly] = loggerRepository;
         }
         return(loggerRepository);
     }
 }
Exemplo n.º 15
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);
						}
					}
				}
			}
		}
        /// <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 !=
        }
Exemplo n.º 17
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));
 }
        /// <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
#if NETSTANDARD1_3
            object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.ConfiguratorAttribute)).ToArray();
#else
            object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false);
#endif
            if (configAttributes != null && configAttributes.Length > 0)
            {
                // Sort the ConfiguratorAttributes in priority order
                Array.Sort(configAttributes);

                // Delegate to the attribute the job of configuring the repository
                foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes)
                {
                    if (configAttr != null)
                    {
                        try
                        {
                            configAttr.Configure(assembly, repository);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex);
                        }
                    }
                }
            }

            if (repository.Name == DefaultRepositoryName)
            {
                // Try to configure the default repository using an AppSettings specified config file
                // Do this even if the repository has been configured (or claims to be), this allows overriding
                // of the default config files etc, if that is required.

                string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config");
                if (repositoryConfigFile != null && repositoryConfigFile.Length > 0)
                {
                    string applicationBaseDirectory = null;
                    try
                    {
                        applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex);
                    }

                    string repositoryConfigFilePath = repositoryConfigFile;
                    if (applicationBaseDirectory != null)
                    {
                        repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile);
                    }

                    // Determine whether to watch the file or not based on an app setting value:
                    bool watchRepositoryConfigFile = false;
#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3
                    Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile);
#else
                    {
                        string watch = SystemInfo.GetAppSetting("log4net.Config.Watch");
                        if (watch != null && watch.Length > 0)
                        {
                            try
                            {
                                watchRepositoryConfigFile = Boolean.Parse(watch);
                            }
                            catch (FormatException)
                            {
                                // simply not a Boolean
                            }
                        }
                    }
#endif

                    if (watchRepositoryConfigFile)
                    {
                        // As we are going to watch the config file it is required to resolve it as a
                        // physical file system path pass that in a FileInfo object to the Configurator
                        FileInfo repositoryConfigFileInfo = null;
                        try
                        {
                            repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex);
                        }
                        try
                        {
                            LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]");

                            XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex);
                        }
                    }
                    else
                    {
                        // As we are not going to watch the config file it is easiest to just resolve it as a
                        // URI and pass that to the Configurator
                        Uri repositoryConfigUri = null;
                        try
                        {
                            repositoryConfigUri = new Uri(repositoryConfigFilePath);
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex);
                        }

                        if (repositoryConfigUri != null)
                        {
                            LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]");

                            try
                            {
                                // TODO: Support other types of configurator
                                XmlConfigurator.Configure(repository, repositoryConfigUri);
                            }
                            catch (Exception ex)
                            {
                                LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 19
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
            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
        }
Exemplo n.º 20
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;
            }
        }
Exemplo n.º 21
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);
                    }
                }
            }
        }
Exemplo n.º 22
0
        /// <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;
            }
        }
Exemplo n.º 23
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)
        {
            string appenderName = appenderElement.GetAttribute(NAME_ATTR);
            string typeName     = appenderElement.GetAttribute(TYPE_ATTR);

            LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]");
            try
            {
#if NETSTANDARD1_3
                IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, typeName, true, true));
#else
                IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true));
#endif
                appender.Name = appenderName;

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

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

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

                                IAppender referencedAppender = this.FindAppenderByReference(currentElement);
                                if (referencedAppender != null)
                                {
                                    appenderContainer.AddAppender(referencedAppender);
                                }
                            }
                            else
                            {
                                LogLog.Error(declaringType, "Requesting attachment of appender named [" + refName + "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable.");
                            }
                        }
                        else
                        {
                            // For all other tags we use standard set param method
                            this.SetParameter(currentElement, appender);
                        }
                    }
                }

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

                LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]");
                return(appender);
            }
            catch (Exception ex)
            {
                // Yes, it's ugly.  But all exceptions point to the same problem: we can't create an Appender
                LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex);
                return(null);
            }
        }
Exemplo n.º 24
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("DefaultRepositorySelector: 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("DefaultRepositorySelector: 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("DefaultRepositorySelector: Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex);
							}
						}
					}
					else
					{
						LogLog.Debug("DefaultRepositorySelector: 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("DefaultRepositorySelector: Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex);
							}
						}
					}
					m_assembly2repositoryMap[repositoryAssembly] = rep;
				}
				return rep;
			}
		}
Exemplo n.º 25
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 || this.m_hierarchy == null)
            {
                return;
            }

            string rootElementName = element.LocalName;

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

            if (!LogLog.EmitInternalMessages)
            {
                // Look for a emitDebug attribute to enable internal debug
                string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
                LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");

                if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
                {
                    LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
                }
            }

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

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

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

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

            // Look for the config update attribute
            string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR);

            if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0)
            {
                // Parse the attribute
                try
                {
                    configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute);
                }
                catch
                {
                    LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]");
                }
            }

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

            // Only reset configuration if overwrite flag specified
            if (configUpdateMode == ConfigUpdateMode.Overwrite)
            {
                // Reset to original unset configuration
                this.m_hierarchy.ResetConfiguration();
                LogLog.Debug(declaringType, "Configuration reset before reading config.");
            }

            /* Building Appender objects, placing them in a local namespace
             * for future reference */

            /* Process all the top level elements */

            foreach (XmlNode currentNode in element.ChildNodes)
            {
                if (currentNode.NodeType == XmlNodeType.Element)
                {
                    XmlElement currentElement = (XmlElement)currentNode;

                    if (currentElement.LocalName == LOGGER_TAG)
                    {
                        this.ParseLogger(currentElement);
                    }
                    else if (currentElement.LocalName == CATEGORY_TAG)
                    {
                        // TODO: deprecated use of category
                        this.ParseLogger(currentElement);
                    }
                    else if (currentElement.LocalName == ROOT_TAG)
                    {
                        this.ParseRoot(currentElement);
                    }
                    else if (currentElement.LocalName == RENDERER_TAG)
                    {
                        this.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
                        this.SetParameter(currentElement, this.m_hierarchy);
                    }
                }
            }

            // Lastly set the hierarchy threshold
            string thresholdStr = element.GetAttribute(THRESHOLD_ATTR);

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

            // Done reading config
        }
Exemplo n.º 26
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("DefaultRepositorySelector: 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("DefaultRepositorySelector: 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("DefaultRepositorySelector: Creating repository [" + repositoryName + "] using type [" + repositoryType + "]");

						// Call the no arg constructor for the repositoryType
						rep = (ILoggerRepository)Activator.CreateInstance(repositoryType);

						// Set the name of the repository
						rep.Name = repositoryName;

						// Store in map
						m_name2repositoryMap[repositoryName] = rep;

						// Notify listeners that the repository has been created
						OnLoggerRepositoryCreatedEvent(rep);
					}
				}

				return rep;
			}
		}
Exemplo n.º 27
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();
                    }
                }
            }
        }
Exemplo n.º 28
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("DefaultRepositorySelector: 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("DefaultRepositorySelector: Assembly [" + assembly + "] does not have a RepositoryAttribute specified.");
				}
				else
				{
					if (repositoryAttributes.Length > 1)
					{
						LogLog.Error("DefaultRepositorySelector: 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("DefaultRepositorySelector: 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("DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface.");
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				LogLog.Error("DefaultRepositorySelector: Unhandled exception in GetInfoForAssembly", ex);
			}
		}
Exemplo n.º 29
0
 /// <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));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Configures the <see cref="ILoggerRepository"/> using the specified XML
        /// element.
        /// </summary>
        /// <remarks>
        /// Loads the log4net configuration from the XML element
        /// supplied as <paramref name="element"/>.
        /// </remarks>
        /// <param name="repository">The repository to configure.</param>
        /// <param name="element">The element to parse.</param>
        static public void Configure(ILoggerRepository repository, XmlElement element)
        {
            LogLog.Debug("DOMConfigurator: configuring repository [" + repository.Name + "] using XML element");

            ConfigureFromXML(repository, element);
        }