Beispiel #1
0
 private static void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
 {
     if (element == null)
     {
         LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
     }
     else if (repository == null)
     {
         LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
     }
     else
     {
         LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");
         IXmlRepositoryConfigurator configurator = repository as IXmlRepositoryConfigurator;
         if (configurator == null)
         {
             LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
         }
         else
         {
             XmlDocument document = new XmlDocument();
             configurator.Configure((XmlElement)document.AppendChild(document.ImportNode(element, true)));
         }
     }
 }
Beispiel #2
0
            /// <summary>
            /// Close all network connections
            /// </summary>
            /// <remarks>
            /// <para>
            /// Make sure we close all network connections
            /// </para>
            /// </remarks>
            public void Dispose()
            {
                ArrayList localClients = m_clients;

                foreach (SocketClient client in localClients)
                {
                    client.Dispose();
                }
                m_clients.Clear();

                Socket localSocket = m_serverSocket;

                m_serverSocket = null;
                try
                {
                    localSocket.Shutdown(SocketShutdown.Both);
                }
                catch
                {
                    LogLog.Warn("Error while trying to shutdown the socket.");
                }

                try
                {
                    localSocket.Close();
                }
                catch
                {
                    LogLog.Warn("Error while trying to close the socket.");
                }
            }
Beispiel #3
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            LogLog.Debug(DeclaringType, string.Format("RaygunAppender: Received Logging Event with Logging Level '{0}'", loggingEvent.Level));

            Exception exception = ResolveLoggedExceptionObject(loggingEvent);

            if (exception != null || !OnlySendExceptions)
            {
                if (Retries > 0)
                {
                    LogLog.Debug(DeclaringType, "RaygunAppender: Retries are enabled, checking that throw on errors has been enabled, or can be overridden");
                    RaygunThrowOnErrorsMustBeEnabled();
                }

                RaygunMessage raygunMessage = BuildRaygunMessageToSend(exception, loggingEvent);

                if (raygunMessage == null)
                {
                    LogLog.Warn(DeclaringType, "RaygunAppender: Failed to send due to an invalid RaygunMessage object");
                }
                else
                {
                    if (SendInBackground)
                    {
                        SendErrorToRaygunInBackground(raygunMessage);
                    }
                    else
                    {
                        SendErrorToRaygun(raygunMessage);
                    }
                }
            }
        }
 private void LogThreadMethod()
 {
     while (true)
     {
         string appenderName = "";
         try
         {
             LoggingEvent loggingEvent = this._logEvents.Take();
             if (loggingEvent != null)
             {
                 foreach (IAppender appender in this.Appenders)
                 {
                     appenderName = appender.Name;
                     appender.DoAppend(loggingEvent);
                 }
             }
             continue;
         }
         catch (ThreadAbortException)
         {
             LogLog.Warn(this.GetType(), "The inner consuming thread is asked to be stopped.");
         }
         catch (ThreadInterruptedException)
         {
             LogLog.Warn(this.GetType(), "The inner consuming thread is asked to be stopped.");
         }
         catch (Exception ex)
         {
             LogLog.Warn(this.GetType(), string.Format("Failure in the independent thread-Appending within {0} : {1}", appenderName, ex));
             Thread.Sleep(1000);
             continue;
         }
         break;
     }
 }
Beispiel #5
0
        /// <summary>
        /// Override the parent method to close the database
        /// </summary>
        /// <remarks>
        /// <para>
        /// Closes the database command and database connection.
        /// </para>
        /// </remarks>
        override protected void OnClose()
        {
            base.OnClose();

            // Close the cached command and connection objects
            if (m_dbCommand != null)
            {
                try
                {
                    m_dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    LogLog.Warn("AdoNetAppender: Exception while disposing cached command object", ex);
                }
                m_dbCommand = null;
            }
            if (m_dbConnection != null)
            {
                try
                {
                    m_dbConnection.Close();
                }
                catch (Exception ex)
                {
                    LogLog.Warn("AdoNetAppender: Exception while disposing cached connection object", ex);
                }
                m_dbConnection = null;
            }
        }
        /// <summary>
        /// Add a log event to the ElasticSearch Repo
        /// </summary>
        /// <param name="loggingEvent"></param>
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (_client == null || loggingEvent == null)
            {
                return;
            }

            if (DropEventsOverBulkLimit && _bulk.Count >= BulkSize)
            {
                _tolerateCalls.Call(() =>
                                    LogLog.Warn(GetType(),
                                                "Message lost due to bulk overflow! Set DropEventsOverBulkLimit to false in order to prevent that."),
                                    GetType(), 0);
                return;
            }

            var logEvent = LogEventFactory.CreateLogEvent(loggingEvent);

            PrepareAndAddToBulk(logEvent);

            if (!DropEventsOverBulkLimit && _bulk.Count >= BulkSize && BulkSize > 0)
            {
                DoIndexNow();
            }
        }
Beispiel #7
0
            /// <summary>
            /// Callback used to accept a connection on the server socket
            /// </summary>
            /// <param name="asyncResult">The result of the asynchronous operation</param>
            /// <remarks>
            /// <para>
            /// On connection adds to the list of connections
            /// if there are two many open connections you will be disconnected
            /// </para>
            /// </remarks>
            private void OnConnect(IAsyncResult asyncResult)
            {
                Socket       socket = m_serverSocket.EndAccept(asyncResult);
                SocketClient client = new SocketClient(socket);

                try
                {
                    LogLog.Trace("TelnetAppender: Accepting connection from [" + socket.RemoteEndPoint.ToString() + "]");

                    int currentActiveConnectionsCount = m_clients.Count;
                    if (currentActiveConnectionsCount < MAX_CONNECTIONS)
                    {
                        client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n");
                        AddClient(client);
                    }
                    else
                    {
                        client.Send("Sorry - Too many connections.\r\n");
                        client.Dispose();
                    }
                }
                catch (Exception)
                {
                    LogLog.Warn("Add connection to list: exception while trying to add connection");
                }
                finally
                {
                    if (m_serverSocket != null)
                    {
                        m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null);
                    }
                }
            }
        /// <summary>
        /// Activate the options on the file appender. This will
        /// case the file to be opened.
        /// </summary>
        override public void ActivateOptions()
        {
            base.ActivateOptions();
            if (m_fileName != null)
            {
                // We must cache the params locally because OpenFile will call
                // Reset which will clear the class fields. We need to remember the
                // values in case of an error.

                string fileName     = m_fileName;
                bool   appendToFile = m_appendToFile;

                try
                {
                    OpenFile(fileName, appendToFile);
                }
                catch (Exception e)
                {
                    ErrorHandler.Error("OpenFile(" + fileName + "," + appendToFile + ") call failed.", e, ErrorCodes.FileOpenFailure);
                }
            }
            else
            {
                LogLog.Warn("FileAppender: File option not set for appender [" + Name + "].");
                LogLog.Warn("FileAppender: Are you using FileAppender instead of ConsoleAppender?");
            }
        }
Beispiel #9
0
        protected void RollFile(string fromFile, string toFile)
        {
            using (SecurityContext.Impersonate(this))
            {
                if (FileExists(fromFile))
                {
                    DeleteFile(toFile);

                    try
                    {
                        LogLog.Debug("RollingFileAppender: Moving [" + fromFile + "] -> [" + toFile + "]");

                        System.IO.File.Move(fromFile, toFile);
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", ex,
                                           ErrorCode.GenericFailure);
                    }
                }
                else
                {
                    LogLog.Warn("RollingFileAppender: Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist");
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Configures the specified repository using a <c>log4net</c> element.
        /// </summary>
        /// <param name="repository">The hierarchy to configure.</param>
        /// <param name="element">The element to parse.</param>
        /// <remarks>
        /// <para>
        /// Loads the log4net configuration from the XML element
        /// supplied as <paramref name="element" />.
        /// </para>
        /// <para>
        /// This method is ultimately called by one of the Configure methods
        /// to load the configuration from an <see cref="T:System.Xml.XmlElement" />.
        /// </para>
        /// </remarks>
        private static void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
        {
            if (element == null)
            {
                LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
                return;
            }
            if (repository == null)
            {
                LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
                return;
            }
            LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");
            IXmlRepositoryConfigurator xmlRepositoryConfigurator = repository as IXmlRepositoryConfigurator;

            if (xmlRepositoryConfigurator == null)
            {
                LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
                return;
            }
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement  element2    = (XmlElement)xmlDocument.AppendChild(xmlDocument.ImportNode(element, deep: true));

            xmlRepositoryConfigurator.Configure(element2);
        }
Beispiel #11
0
        protected void RollFile(string fromFile, string toFile)
        {
            if (FileExists(fromFile))
            {
                // Delete the toFile if it exists
                DeleteFile(toFile);

                // We may not have permission to move the file, or the file may be locked
                try
                {
                    LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]");
                    using (SecurityContext.Impersonate(this))
                    {
                        System.IO.File.Move(fromFile, toFile);
                    }
                }
                catch (Exception moveEx)
                {
                    ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure);
                }
            }
            else
            {
                LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist");
            }
        }
Beispiel #12
0
 protected void RollFile(string fromFile, string toFile)
 {
     if (File.Exists(fromFile))
     {
         // Delete the toFile if it exists
         DeleteFile(toFile);
         int retries = 3;
         while (retries != 0)
         {
             // We may not have permission to move the file, or the file may be locked
             try
             {
                 LogLog.Debug("RollingFileAppender: Moving [" + fromFile + "] -> [" + toFile + "]");
                 File.Move(fromFile, toFile);
                 retries = 0;
             }
             catch (Exception moveEx)
             {
                 ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]",
                                    moveEx,
                                    ErrorCode.GenericFailure);
                 retries--;
             }
         }
     }
     else
     {
         LogLog.Warn("RollingFileAppender: Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist");
     }
 }
Beispiel #13
0
        private bool TerminateInternal(int timeoutMs, StateKind state, string action)
        {
            lock (myLock)
            {
                if (State == StateKind.Initialized)
                {
                    LogLog.Verbose(LogCategory, "Can't {1} '{0}', because it hasn't been started yet", Id, action);
                    CleanupInternal();
                    return(true);
                }

                if (State >= state)
                {
                    LogLog.Verbose(LogCategory, "Trying to {2} async processor '{0}' but it's in state '{1}'", Id, State, action);
                    return(true);
                }

                State = state;
                Monitor.Pulse(myLock);
            }

            var res = myAsyncProcessingThread.Join(timeoutMs);

            if (!res)
            {
                LogLog.Warn($"Async processor {Id} hasn't finished in ${timeoutMs} ms. Trying to abort thread.");
                LogLog.Catch(() => myAsyncProcessingThread.Abort());
            }

            CleanupInternal();
            return(res);
        }
Beispiel #14
0
        /// <summary>
        /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread.
        /// </summary>
        /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param>
        /// <returns>the properties for this thread</returns>
        /// <remarks>
        /// <para>
        /// The collection returned is only to be used on the calling thread. If the
        /// caller needs to share the collection between different threads then the
        /// caller must clone the collection before doings so.
        /// </para>
        /// <para>
        /// 封装了一层从 CallContext 拿取数据(get)的方法,并包装了异常处理
        /// </para>
        /// </remarks>
        internal PropertiesDictionary GetProperties(bool create)
        {
            if (!m_disabled)
            {
                try
                {
                    PropertiesDictionary properties = GetLogicalProperties();
                    if (properties == null && create)
                    {
                        properties = new PropertiesDictionary();
                        SetLogicalProperties(properties);
                    }
                    return(properties);
                }
                catch (SecurityException secEx)
                {
                    m_disabled = true;

                    // Thrown if we don't have permission to read or write the CallContext
                    LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx);
                }
            }

            // Only get here is we are disabled because of a security exception
            if (create)
            {
                return(new PropertiesDictionary());
            }
            return(null);
        }
Beispiel #15
0
        /// <summary>
        /// Activate the options on the file appender.
        /// </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>
        /// <para>
        /// This will cause the file to be opened.
        /// </para>
        /// </remarks>
        override public void ActivateOptions()
        {
            base.ActivateOptions();

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

            if (m_lockingModel == null)
            {
                m_lockingModel = new FileAppender.ExclusiveLock();
            }

            m_lockingModel.CurrentAppender = this;

            using (SecurityContext.Impersonate(this))
            {
                // john.torjo - we need this to be relative to user's roaming dir
                //              deriving a class from FileAppender and overriding ActivateOptions() is useless,
                //              since what we need to set are private to this class - so easier to just modify this code:
                //m_fileName = ConvertToFullPath(m_fileName.Trim());
                m_fileName = Environment.CurrentDirectory + "\\" + m_fileName.Trim();
            }

            if (m_fileName != null)
            {
                SafeOpenFile(m_fileName, m_appendToFile);
            }
            else
            {
                LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + Name + "].");
                LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?");
            }
        }
Beispiel #16
0
        /// <summary>
        /// Configures the specified repository using a <c>log4net</c> element.
        /// </summary>
        /// <param name="repository">The hierarchy to configure.</param>
        /// <param name="element">The element to parse.</param>
        /// <remarks>
        /// <para>
        /// Loads the log4net configuration from the XML element
        /// supplied as <paramref name="element"/>.
        /// </para>
        /// <para>
        /// This method is ultimately called by one of the Configure methods
        /// to load the configuration from an <see cref="XmlElement"/>.
        /// </para>
        /// </remarks>
        static private void ConfigureFromXML(ILoggerRepository repository, XmlElement element)
        {
            if (element == null)
            {
                LogLog.Error("DOMConfigurator: ConfigureFromXML called with null 'element' parameter");
            }
            else if (repository == null)
            {
                LogLog.Error("DOMConfigurator: ConfigureFromXML called with null 'repository' parameter");
            }
            else
            {
                LogLog.Debug("DOMConfigurator: Configuring Repository [" + repository.Name + "]");

                // Copy the xml data into the root of a new document
                // this isolates the xml config data from the rest of
                // the document
                XmlDocument newDoc     = new XmlDocument();
                XmlElement  newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));

                // Check the type of the repository
                if (repository is IDOMRepositoryConfigurator)
                {
                    // Pass the configurator the config element
                    ((IDOMRepositoryConfigurator)repository).Configure(newElement);
                }
                else
                {
                    LogLog.Warn("Repository [" + repository + "] does not support the DOMConfigurator");
                }
            }
        }
        /// <summary>
        /// Appends a new message to the asynchronous buffer
        /// </summary>
        /// <param name="loggingEvent">Logging event with the message</param>
        protected override void Append(LoggingEvent loggingEvent)
        {
            try
            {
                loggingEvent.Fix = FixFlags.All;
                if (!this.eventsQueue.IsAddingCompleted)
                {
                    int droppedCount = 0;

                    // Add new events in a rolling buffer fashion
                    while (!this.eventsQueue.TryAdd(loggingEvent))
                    {
                        this.eventsQueue.TryTake(out _);
                        droppedCount++;
                    }

                    if (droppedCount > 0)
                    {
                        LogLog.Warn(this.GetType(), $"{droppedCount} log events have been dropped, RollingBufferSize={this.RollingBufferSize} has been reached");
                    }
                }
            }
            catch (Exception ex)
            {
                this.ErrorHandler.Error("Exception occurred in AsyncAppender wrapper", ex);
            }
        }
Beispiel #18
0
        protected override void OnClose()
        {
            Exception exception;

            base.OnClose();
            if (this.m_dbCommand != null)
            {
                try
                {
                    this.m_dbCommand.Dispose();
                }
                catch (Exception exception1)
                {
                    exception = exception1;
                    LogLog.Warn("AdoNetAppender: Exception while disposing cached command object", exception);
                }
                this.m_dbCommand = null;
            }
            if (this.m_dbConnection != null)
            {
                try
                {
                    this.m_dbConnection.Close();
                }
                catch (Exception exception2)
                {
                    exception = exception2;
                    LogLog.Warn("AdoNetAppender: Exception while disposing cached connection object", exception);
                }
                this.m_dbConnection = null;
            }
        }
        /// <summary>
        /// This override will delete logs older than the specified amount of days
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="append"></param>
        protected override void OpenFile(string fileName, bool append)
        {
            bool cleanup = true;

            // Validate settings and input
            if (MaxLogFileDays <= 0)
            {
                LogLog.Warn(typeof(RollingFileCleanupAppender), "Parameter 'MaxLogFileDays' needs to be a positive integer, aborting cleanup");
                cleanup = false;
            }

            if (string.IsNullOrWhiteSpace(BaseFilePattern))
            {
                LogLog.Warn(typeof(RollingFileCleanupAppender), "Parameter 'BaseFilePattern' is empty, aborting cleanup");
                cleanup = false;
            }
            // grab the directory we are logging to, as this is were we will search for older logfiles
            var logFolder = Path.GetDirectoryName(fileName);

            if (Directory.Exists(logFolder) == false)
            {
                LogLog.Warn(typeof(RollingFileCleanupAppender), string.Format("Directory '{0}' for logfiles does not exist, aborting cleanup", logFolder));
                cleanup = false;
            }
            // If everything is validated, we can do the actual cleanup
            if (cleanup)
            {
                Cleanup(logFolder);
            }

            base.OpenFile(fileName, append);
        }
        /// <summary>
        /// Configures the specified repository using a <c>log4net</c> element.
        /// </summary>
        /// <param name="repository">The hierarchy to configure.</param>
        /// <param name="element">The element to parse.</param>
        /// <remarks>
        /// <para>
        /// Loads the log4net configuration from the XML element
        /// supplied as <paramref name="element"/>.
        /// </para>
        /// <para>
        /// This method is ultimately called by one of the Configure methods
        /// to load the configuration from an <see cref="XmlElement"/>.
        /// </para>
        /// </remarks>
        static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
        {
            if (element == null)
            {
                LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
            }
            else if (repository == null)
            {
                LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
            }
            else
            {
                LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");

                IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
                if (configurableRepository == null)
                {
                    LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
                }
                else
                {
                    // Copy the xml data into the root of a new document
                    // this isolates the xml config data from the rest of
                    // the document
                    XmlDocument newDoc     = new XmlDocument();
                    XmlElement  newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));

                    // Pass the configurator the config element
                    configurableRepository.Configure(newElement);
                }
            }
        }
 protected override void SendBuffer(log4net.Core.LoggingEvent[] events)
 {
     if (ConfirmChannelAcceptable())
     {
         try
         {
             if (this.RenderOnClient)
             {
                 string[] logs = new string[events.Length];
                 for (int i = 0; i < events.Length; i++)
                 {
                     logs[i] = base.RenderLoggingEvent(events[i]);
                 }
                 _LoggingService.Append(logs);
             }
             else
             {
                 LoggingEventWrapper[] wrappers = new LoggingEventWrapper[events.Length];
                 for (int i = 0; i < events.Length; i++)
                 {
                     wrappers[i] = new LoggingEventWrapper(events[i]);
                 }
                 _LoggingService.Append(wrappers);
             }
         }
         catch (Exception ex)
         {
             LogLog.Error(typeDescriptor, "Error sending log events to remoe endpoint", ex);
         }
     }
     else
     {
         LogLog.Warn(typeDescriptor, "WCF Channel cannot be confirmed as acceptable, not sending events");
     }
 }
Beispiel #22
0
 /// <summary>
 /// Activate the options on the file appender.
 /// </summary>
 /// <remarks>
 /// <para>
 /// This is part of the <see cref="T:log4net.Core.IOptionHandler" /> delayed object
 /// activation scheme. The <see cref="M:log4net.Appender.FileAppender.ActivateOptions" /> method must
 /// be called on this object after the configuration properties have
 /// been set. Until <see cref="M:log4net.Appender.FileAppender.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="M:log4net.Appender.FileAppender.ActivateOptions" /> must be called again.
 /// </para>
 /// <para>
 /// This will cause the file to be opened.
 /// </para>
 /// </remarks>
 public override void ActivateOptions()
 {
     base.ActivateOptions();
     if (m_securityContext == null)
     {
         m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
     }
     if (m_lockingModel == null)
     {
         m_lockingModel = new ExclusiveLock();
     }
     m_lockingModel.CurrentAppender = this;
     m_lockingModel.ActivateOptions();
     if (m_fileName != null)
     {
         using (SecurityContext.Impersonate(this))
         {
             m_fileName = ConvertToFullPath(m_fileName.Trim());
         }
         SafeOpenFile(m_fileName, m_appendToFile);
     }
     else
     {
         LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + base.Name + "].");
         LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?");
     }
 }
Beispiel #23
0
 private void RaygunThrowOnErrorsMustBeEnabled()
 {
     if (!RaygunSettings.Settings.ThrowOnError)
     {
         LogLog.Warn(DeclaringType, "RaygunAppender: ThrowOnError was found to be disabled, setting to 'true'");
         RaygunSettings.Settings.ThrowOnError = true;
     }
 }
        public override void ActivateOptions()
        {
            LogLog.Debug(declaringType, "Debug - Activating options...");
            LogLog.Warn(declaringType, "Warn - Activating options...");
            LogLog.Error(declaringType, "Error - Activating options...");

            base.ActivateOptions();
        }
Beispiel #25
0
        /// <summary>
        /// Formats email's subject using <see cref="SubjectLayout"/>.
        ///
        /// <see cref="AppenderSkeleton.RenderLoggingEvent(TextWriter, log4net.Core.LoggingEvent)"/>
        /// </summary>
        /// <param name="loggingEvent"></param>
        protected void FormatSubject(LoggingEvent loggingEvent)
        {
            var layout = SubjectLayout;

            if (layout == null)
            {
                LogLog.Warn("SmtpAppender: No subjectLayout configured for appender [" + Name + "]");
                return;
            }

            var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);

            if (layout.IgnoresException)
            {
                string exceptionStr = loggingEvent.GetExceptionString();
                if (!string.IsNullOrEmpty(exceptionStr))
                {
                    // render the event and the exception
                    layout.Format(writer, loggingEvent);
                    writer.WriteLine(exceptionStr);
                }
                else
                {
                    // there is no exception to render
                    layout.Format(writer, loggingEvent);
                }
            }
            else
            {
                // The layout will render the exception
                layout.Format(writer, loggingEvent);
            }

            string subject = writer.ToString();

            //  Take first line only (Subject may not contain any control chars)
            var idx = subject.IndexOf("\r\n");

            if (idx != -1)
            {
                subject = subject.Substring(0, idx);
            }

            //  Cut subject to specified length
            if (!string.IsNullOrEmpty(SubjectMaxLength))
            {
                int maxLength;
                if (int.TryParse(SubjectMaxLength, out maxLength))
                {
                    if (maxLength > 0 && subject.Length > maxLength)
                    {
                        subject = subject.Substring(0, maxLength);
                    }
                }
            }

            Subject = subject;
        }
Beispiel #26
0
        /// <summary>
        /// Initialize internal epoch time reference cache, thread safe
        /// </summary>
        public static void Init()
        {
            // init only if not done yet, thread safe

            if (s_ref_sys_time == 0)
            {
                lock (s_sync_root)
                {
                    // Check if someone else was faster
                    if (s_ref_sys_time != 0)
                    {
                        return;
                    }

                    // First we work with the NOW now, to get precise system start time

                    var now    = DateTime.UtcNow;
                    var uptime = GetSystemUpTime();
                    var epoch  = DateTime.ParseExact("1970", "yyyy", CultureInfo.InvariantCulture);
                    var espan  = now - epoch;

                    s_ref_app_time = ConvertTimeSpanToSeconds(espan);
                    s_ref_sys_time = s_ref_app_time - uptime;

                    // Then try get the actual application start time. The 'NOW now' was possibly the time of the first logging event

                    try
                    {
                        espan          = Process.GetCurrentProcess().StartTime.ToUniversalTime() - epoch;
                        s_ref_app_time = ConvertTimeSpanToSeconds(espan);
                    }
                    catch (Exception x)
                    {
#if LOG4NET_1_2_10_COMPATIBLE
                        LogLog.Warn("PropertyTimeStamp.Init() - getting exact app start time failed, but we should be fine with approximate time.", x);
#else
                        LogLog.Warn(typeof(TimeStamp), "PropertyTimeStamp.Init() - getting exact app start time failed, but we should be fine with approximate time.", x);
#endif
                    }

                    try
                    {
                        s_processId = System.Diagnostics.Process.GetCurrentProcess().Id;
                    }
                    catch (Exception x)
                    {
#if LOG4NET_1_2_10_COMPATIBLE
                        LogLog.Warn("PropertyTimeStamp.Init() - getting process id failed, leaving -1.", x);
#else
                        LogLog.Warn(typeof(TimeStamp), "PropertyTimeStamp.Init() - getting process id failed, leaving -1.", x);
#endif
                        s_processId = -1;
                    }
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Attempt to load configuration from the local file system
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            string text = null;

            if (m_configFile == null || m_configFile.Length == 0)
            {
                if (m_configFileExtension == null || m_configFileExtension.Length == 0)
                {
                    try
                    {
                        text = SystemInfo.ConfigurationFileLocation;
                    }
                    catch (Exception exception)
                    {
                        LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", exception);
                    }
                }
                else
                {
                    if (m_configFileExtension[0] != '.')
                    {
                        m_configFileExtension = "." + m_configFileExtension;
                    }
                    string text2 = null;
                    try
                    {
                        text2 = SystemInfo.ApplicationBaseDirectory;
                    }
                    catch (Exception exception2)
                    {
                        LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", exception2);
                    }
                    if (text2 != null)
                    {
                        text = Path.Combine(text2, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension);
                    }
                }
            }
            else
            {
                string text3 = null;
                try
                {
                    text3 = SystemInfo.ApplicationBaseDirectory;
                }
                catch (Exception exception3)
                {
                    LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + m_configFile + "] will be treated as an absolute path.", exception3);
                }
                text = ((text3 == null) ? m_configFile : Path.Combine(text3, m_configFile));
            }
            if (text != null)
            {
                ConfigureFromFile(targetRepository, new FileInfo(text));
            }
        }
 protected override void Append(LoggingEvent loggingEvent)
 {
     if (this._logEvents.Count < MAX_QUEUE_COUNT)
     {
         loggingEvent.Fix = FixFlags.ThreadName;
         this._logEvents.Add(loggingEvent);
         return;
     }
     LogLog.Warn(this.GetType(), "Queue is full, drop the overflow log message!");
 }
Beispiel #29
0
            private Mutex CreateMutex()
            {
                m_mutexname = GetMutexName(m_filename);

                try
                {
                    // Open the mutex.
                    m_mutex = Mutex.OpenExisting(m_mutexname);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    // The named mutex does not exist.
                    MutexSecurity mSec = new MutexSecurity();

                    MutexAccessRule rule = new MutexAccessRule(
                        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                        MutexRights.FullControl, AccessControlType.Allow);
                    mSec.AddAccessRule(rule);

                    bool mutexWasCreated;
                    m_mutex = new Mutex(false, m_mutexname, out mutexWasCreated, mSec);
                }
                catch (UnauthorizedAccessException)
                {
                    // The named mutex exists, but the user does not have the security access required to use it.
                    LogLog.Warn(typeof(FileAppender), "The named mutex exists, but the user does not have the security access required to use it.");
                    try
                    {
                        m_mutex = Mutex.OpenExisting(m_mutexname, MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                        // Get the current ACL. This requires MutexRights.ReadPermissions.
                        MutexSecurity mSec = m_mutex.GetAccessControl();

                        // Now grant the user the correct rights.
                        MutexAccessRule rule = new MutexAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                            MutexRights.FullControl, AccessControlType.Allow);
                        mSec.AddAccessRule(rule);

                        // Update the ACL. This requires MutexRights.ChangePermissions.
                        m_mutex.SetAccessControl(mSec);

                        LogLog.Debug(typeof(FileAppender), "Updated mutex security.");

                        m_mutex = Mutex.OpenExisting(m_mutexname);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        LogLog.Error(typeof(FileAppender), "Unable to change permissions on mutex.", ex);
                        m_mutex = new Mutex(false, m_mutexname);
                    }
                }

                return(m_mutex);
            }
 private void CheckObsoleteAuth()
 {
     if (!string.IsNullOrEmpty(BasicAuthUsername) && !string.IsNullOrEmpty(BasicAuthPassword))
     {
         LogLog.Warn(GetType(), "BasicAuthUsername & BasicAuthPassword tags are obsolete, Please use AuthenticationMethod new tag");
         var auth = new BasicAuthenticationMethod {
             Username = BasicAuthUsername, Password = BasicAuthPassword
         };
         AuthenticationMethod.AddBasic(auth);
     }
 }