Exemple #1
0
 /// <summary>Sets the slf4j <code>MDC</code> and delegates the request to the chain.</summary>
 /// <param name="request">servlet request.</param>
 /// <param name="response">servlet response.</param>
 /// <param name="chain">filter chain.</param>
 /// <exception cref="System.IO.IOException">thrown if an IO error occurrs.</exception>
 /// <exception cref="Javax.Servlet.ServletException">thrown if a servet error occurrs.
 ///     </exception>
 public virtual void DoFilter(ServletRequest request, ServletResponse response, FilterChain
                              chain)
 {
     try
     {
         MDC.Clear();
         string hostname = HostnameFilter.Get();
         if (hostname != null)
         {
             MDC.Put("hostname", HostnameFilter.Get());
         }
         Principal principal = ((HttpServletRequest)request).GetUserPrincipal();
         string    user      = (principal != null) ? principal.GetName() : null;
         if (user != null)
         {
             MDC.Put("user", user);
         }
         MDC.Put("method", ((HttpServletRequest)request).GetMethod());
         MDC.Put("path", ((HttpServletRequest)request).GetPathInfo());
         chain.DoFilter(request, response);
     }
     finally
     {
         MDC.Clear();
     }
 }
Exemple #2
0
        public virtual void Mdc()
        {
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();

            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(null);
            Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn("METHOD");
            Org.Mockito.Mockito.When(request.GetPathInfo()).ThenReturn("/pathinfo");
            ServletResponse response = Org.Mockito.Mockito.Mock <ServletResponse>();
            AtomicBoolean   invoked  = new AtomicBoolean();
            FilterChain     chain    = new _FilterChain_55(invoked);

            MDC.Clear();
            Filter filter = new MDCFilter();

            filter.Init(null);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            NUnit.Framework.Assert.IsNull(MDC.Get("hostname"));
            NUnit.Framework.Assert.IsNull(MDC.Get("user"));
            NUnit.Framework.Assert.IsNull(MDC.Get("method"));
            NUnit.Framework.Assert.IsNull(MDC.Get("path"));
            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(new _Principal_78
                                                                                ());
            invoked.Set(false);
            chain = new _FilterChain_86(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Set("HOST");
            invoked.Set(false);
            chain = new _FilterChain_103(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Remove();
            filter.Destroy();
        }
        protected override void Append(LoggingEvent loggingEvent)
        {
            MDC.Set("StateID", StateManager.currentState.ToString());
            var message = RenderLoggingEvent(loggingEvent);

            switch (loggingEvent.Level.Name)
            {
            case "DEBUG":
            case "INFO":
                Debug.Log(message);
                break;

            case "WARN":
                Debug.LogWarning(message);
                break;

            case "ERROR":
                Debug.LogError(message);
                break;

            default:
                break;
            }
            MDC.Clear();
        }
Exemple #4
0
        public void MDCTest2()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 500;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MDC.Clear();
                        Assert.IsFalse(MDC.Contains("foo"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo"));
                        Assert.IsFalse(MDC.Contains("foo2"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo2"));

                        MDC.Set("foo", "bar");
                        MDC.Set("foo2", "bar2");

                        Assert.IsTrue(MDC.Contains("foo"));
                        Assert.AreEqual("bar", MDC.Get("foo"));

                        MDC.Remove("foo");
                        Assert.IsFalse(MDC.Contains("foo"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo"));

                        Assert.IsTrue(MDC.Contains("foo2"));
                        Assert.AreEqual("bar2", MDC.Get("foo2"));
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            if (exceptions.Count != 0)
            {
                Assert.Fail(exceptions[0].ToString());
            }
        }
Exemple #5
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            //Add state ID to any
            MDC.Set(STATE_ID, StateManager.currentState.ToString());

            //Remove rich text for file logging
            string logMessage = Regex.Replace(RenderLoggingEvent(loggingEvent), MARKDOWN_REGEX, String.Empty);

            File.AppendAllText(LOG_FILE, logMessage);

            MDC.Clear();
        }
Exemple #6
0
        //Write and entry to the log table (for use when an HttpContext is not available...)
        public void createLogEntry(string sessionId, string userIpAddress, string domainName, DateTime occurrenceDtUtc, string methodName, Exception exception, string exceptionMessage)
        {
            //Validate/initialize input parameters...
            if (String.IsNullOrWhiteSpace(sessionId) ||
                String.IsNullOrWhiteSpace(userIpAddress) ||
                String.IsNullOrWhiteSpace(domainName) ||
                null == occurrenceDtUtc ||
                String.IsNullOrWhiteSpace(methodName) ||
                null == exception ||
                String.IsNullOrWhiteSpace(exceptionMessage))
            {
                return;                         //Invalid parameter - return early...
            }

            //Write derived and input values to MDC...
            MDC.Clear();

            MDC.Set("SessionId", sessionId);
            MDC.Set("IPAddress", userIpAddress);
            MDC.Set("Domain", domainName);
            MDC.Set("OccurrenceDateTime", occurrenceDtUtc.ToString());
            MDC.Set("MethodName", methodName);
            MDC.Set("ExceptionType", exception.GetType().ToString());
            MDC.Set("ExceptionMessage", exceptionMessage);

            //Convert parameters to JSON and write to MDC...
            //Source: http://stackoverflow.com/questions/23729477/converting-dictionary-string-string-to-json-string
            if (0 < m_dictParams.Count)
            {
                var    kvs  = m_dictParams.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
                string json = string.Concat("{", string.Join(",", kvs), "}");

                MDC.Set("Parameters", json);
            }

            //Write to the log...
            string logMessage = "log message";                  //NOTE: Due to MDC usage and AdoNetAppender usage, this message is not logged..

            m_loggerDB.Error(logMessage);

            //Processing complete - return
            return;
        }
        public void MDCTest2()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 100;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MDC.Clear();
                        Assert.False(MDC.Contains("foo"));
                        Assert.Equal(string.Empty, MDC.Get("foo"));
                        Assert.False(MDC.Contains("foo2"));
                        Assert.Equal(string.Empty, MDC.Get("foo2"));

                        MDC.Set("foo", "bar");
                        MDC.Set("foo2", "bar2");

                        Assert.True(MDC.Contains("foo"));
                        Assert.Equal("bar", MDC.Get("foo"));

                        MDC.Remove("foo");
                        Assert.False(MDC.Contains("foo"));
                        Assert.Equal(string.Empty, MDC.Get("foo"));

                        Assert.True(MDC.Contains("foo2"));
                        Assert.Equal("bar2", MDC.Get("foo2"));

                        Assert.Null(MDC.GetObject("foo3"));
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            StringBuilder exceptionsMessage = new StringBuilder();

            foreach (var ex in exceptions)
            {
                if (exceptionsMessage.Length > 0)
                {
                    exceptionsMessage.Append("\r\n");
                }

                exceptionsMessage.Append(ex.ToString());
            }

            Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
        }
Exemple #8
0
        //Write and entry to the log table (for use when an HttpContext is not available...)
        public void createLogEntry(string sessionId, string userIpAddress, string domainName, string userEMailAddress, DateTime startDtUtc, DateTime endDtUtc, string methodName, string message, Level logLevel)
        {
            //Validate/initialize input parameters...
            if (String.IsNullOrWhiteSpace(sessionId) ||
                String.IsNullOrWhiteSpace(userIpAddress) ||
                String.IsNullOrWhiteSpace(domainName) ||
                String.IsNullOrWhiteSpace(userEMailAddress) ||
                null == startDtUtc ||
                null == endDtUtc ||
                String.IsNullOrWhiteSpace(methodName) ||
                String.IsNullOrWhiteSpace(message) ||
                null == logLevel)
            {
                return;                         //Invalid parameter - return early...
            }

            //Write derived and input values to MDC...
            MDC.Clear();

            MDC.Set("SessionId", sessionId);
            MDC.Set("IPAddress", userIpAddress);
            MDC.Set("Domain", domainName);
            MDC.Set("EmailAddress", userEMailAddress);

            MDC.Set("StartDateTime", startDtUtc.ToString());
            MDC.Set("EndDateTime", endDtUtc.ToString());
            MDC.Set("MethodName", methodName);
            MDC.Set("Message", message);
            MDC.Set("LogLevel", logLevel.DisplayName);

            //Convert parameters to JSON and write to MDC...
            //Source: http://stackoverflow.com/questions/23729477/converting-dictionary-string-string-to-json-string
            if (0 < m_dictParams.Count)
            {
                var    kvs  = m_dictParams.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
                string json = string.Concat("{", string.Join(",", kvs), "}");

                MDC.Set("Parameters", json);
            }

            //Convert returns to JSON and write to MDC...
            if (0 < m_dictReturns.Count)
            {
                var    kvs  = m_dictReturns.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
                string json = string.Concat("{", string.Join(",", kvs), "}");

                MDC.Set("Returns", json);
            }

            //Write to the log per the input level...
            string logMessage = "log message";                  //NOTE: Due to MDC usage and AdoNetAppender usage, this message is not logged..

            if (Level.Debug == logLevel)
            {
                m_loggerDB.Debug(logMessage);
            }
            else if (Level.Error == logLevel)
            {
                m_loggerDB.Error(logMessage);
            }
            else if (Level.Fatal == logLevel)
            {
                m_loggerDB.Fatal(logMessage);
            }
            else if (Level.Info == logLevel)
            {
                m_loggerDB.Info(logMessage);
            }
            else if (Level.Warn == logLevel)
            {
                m_loggerDB.Warn(logMessage);
            }

            //Processing complete - return
            return;
        }