コード例 #1
0
        private static bool Log(LogLevel logLevel, Func <string> messageFunc, Exception exception,
                                params object[] formatParameters)
        {
            string message = null;

            if (messageFunc != null)
            {
                message = messageFunc();
                if (formatParameters != null)
                {
                    message =
                        LogMessageFormatter.FormatStructuredMessage(message,
                                                                    formatParameters,
                                                                    out _);
                }
            }

            if (message != null || exception != null)
            {
                lock (_lock)
                {
                    Logs.Add(Tuple.Create(logLevel, message, exception));
                }
            }

            return(true);
        }
コード例 #2
0
        public void FormatMessage_should_replace_placeholders_named_like_parameters()
        {
            var properties = new Dictionary <string, object> {
                { "0", "value1" }, { "1", "value2" }
            };

            LogMessageFormatter.FormatMessage("aa{0}bb{1}cc", properties).Should().BeEquivalentTo("aavalue1bbvalue2cc");
        }
コード例 #3
0
        public void FormatMessage_should_replace_whitespace_placeholders_if_such_key_exists_in_props()
        {
            var properties = new Dictionary <string, object> {
                { " ", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{ }bb", properties).Should().BeEquivalentTo("aavaluebb");
        }
コード例 #4
0
        public void FormatMessage_should_replace_two_placeholders_if_they_have_not_separators_between_them()
        {
            var properties = new Dictionary <string, object> {
                { "prop1", "value1" }, { "prop2", "value2" }
            };

            LogMessageFormatter.FormatMessage("{prop1}{prop2}", properties).Should().BeEquivalentTo("value1value2");
        }
コード例 #5
0
        public void FormatMessage_should_replace_two_placeholders()
        {
            var properties = new Dictionary <string, object> {
                { "prop1", "value1" }, { "prop2", "value2" }
            };

            LogMessageFormatter.FormatMessage("aa{prop1}bb{prop2}cc", properties).Should().BeEquivalentTo("aavalue1bbvalue2cc");
        }
コード例 #6
0
        public void FormatMessage_should_not_ignore_case_if_props_are_not_ignorecased()
        {
            var properties = new Dictionary <string, object> {
                { "Prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{prop}bb", properties).Should().BeEquivalentTo("aa{prop}bb");
        }
コード例 #7
0
        public void FormatMessage_should_replace_placeholder_if_template_starts_with_it()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("{prop}bb", properties).Should().BeEquivalentTo("valuebb");
        }
コード例 #8
0
        public void FormatMessage_should_replace_placeholder_before_right_brace_when_separator_between_them_exists()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("bb{prop}cc}dd", properties).Should().BeEquivalentTo("bbvaluecc}dd");
        }
コード例 #9
0
        public void FormatMessage_should_replace_only_deepest_placeholders()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{bb{prop}cc}dd", properties).Should().BeEquivalentTo("aa{bbvaluecc}dd");
        }
コード例 #10
0
        public void FormatMessage_should_correctly_render_null_property_values()
        {
            var properties = new Dictionary <string, object> {
                { "prop", null }
            };

            LogMessageFormatter.FormatMessage("aa {prop} bb", properties).Should().BeEquivalentTo("aa null bb");
        }
コード例 #11
0
        public void When_arguments_are_unique_and_not_escaped_Then_should_replace_them()
        {
            Func <string> messageBuilder = () => "This is an {1argument} and this another {argument2} and a last one {2}.";

            var formattedMessage = LogMessageFormatter.SimulateStructuredLogging(messageBuilder, new object[] { "arg0", "arg1", "arg2" })();

            formattedMessage.ShouldBe("This is an arg0 and this another arg1 and a last one arg2.");
        }
コード例 #12
0
        public void FormatMessage_should_replace_placeholder_with_tripled_braces()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("{{{prop}}}", properties).Should().BeEquivalentTo("{value}");
        }
コード例 #13
0
        public void Should_respect_case_sensitivity_in_templates()
        {
            var event1 = new LogEvent(LogLevel.Info, DateTimeOffset.Now, "Hello, {User}!").WithProperty("User", "Kontur");
            var event2 = new LogEvent(LogLevel.Info, DateTimeOffset.Now, "HELLO, {User}!").WithProperty("User", "Kontur");

            LogMessageFormatter.Format(event1).Should().Be("Hello, Kontur!");
            LogMessageFormatter.Format(event2).Should().Be("HELLO, Kontur!");
        }
コード例 #14
0
        public void FormatMessage_should_work_correctly_if_template_starts_with_right_brace()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("}aa", properties).Should().BeEquivalentTo("}aa");
        }
コード例 #15
0
        public void When_arguments_are_escaped_Then_should_not_replace_them()
        {
            Func <string> messageBuilder = () => "This is an {argument} and this an {{escaped_argument}}.";

            var formattedMessage = LogMessageFormatter.SimulateStructuredLogging(messageBuilder, new object[] { "arg0", "arg1" })();

            formattedMessage.ShouldBe("This is an arg0 and this an {escaped_argument}.");
        }
コード例 #16
0
        public void FormatMessage_should_not_replace_placeholder_without_right_brace()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{prop", properties).Should().BeEquivalentTo("aa{prop");
        }
コード例 #17
0
        public void FormatMessage_should_not_replace_placeholder_if_left_brace_is_doubled()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{{prop}bb", properties).Should().BeEquivalentTo("aa{prop}bb");
        }
コード例 #18
0
        public void FormatMessage_should_not_replace_placeholder_with_doubled_braces_if_template_ends_with_it()
        {
            var properties = new Dictionary <string, object> {
                { "prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{{prop}}", properties).Should().BeEquivalentTo("aa{prop}");
        }
コード例 #19
0
        public void FormatMessage_should_ignore_case_if_props_are_ignorecased()
        {
            var properties = new Dictionary <string, object>(StringComparer.CurrentCultureIgnoreCase)
            {
                { "Prop", "value" }
            };

            LogMessageFormatter.FormatMessage("aa{prop}bb", properties).Should().BeEquivalentTo("aavaluebb");
        }
コード例 #20
0
        public bool UpdateItemsGuid(Item item)
        {
            IntegrationConfigData integrationData = null;

            try
            {
                integrationData = IntegrationConfigDataProvider.GetFromItem(item);

                Assert.IsNotNull(integrationData, "integrationData");

                var context = SpContextProviderBase.Instance.CreateDataContext(integrationData);
                var list    = BaseList.GetList(integrationData.Web, integrationData.List, context);

                Assert.IsNotNull(list, "list");

                var itemCollection = list.GetItems(new ItemsRetrievingOptions
                {
                    Folder    = integrationData.Folder,
                    ItemLimit = integrationData.ItemLimit,
                    ViewName  = integrationData.View
                });

                foreach (var listItem in itemCollection)
                {
                    var connectedItem = this.GetConnectedItem(item, listItem, list);

                    if (connectedItem != null)
                    {
                        using (new SecurityDisabler())
                        {
                            new IntegrationItem(connectedItem).GUID = listItem.GUID;
                        }

                        if (listItem is FolderItem)
                        {
                            this.UpdateItemsGuid(connectedItem);
                        }
                    }
                }

                return(true);
            }
            catch (Exception exception)
            {
                var errorMessage = new StringBuilder("Updating guids have been failed.");
                errorMessage.AppendLine(string.Format("Integration config item: {0}", item.ID));

                if (integrationData != null)
                {
                    errorMessage.AppendLine(LogMessageFormatter.FormatWeb01List23(integrationData));
                }

                Log.Error(errorMessage.ToString(), exception, this);

                return(false);
            }
        }
コード例 #21
0
        public void When_argument_is_multiple_time_Then_should_be_replaced_with_same_value()
        {
            var           date           = DateTime.Today;
            Func <string> messageBuilder = () => "{date:yyyy-MM-dd} {argument1} {date:yyyy}";

            var formattedMessage = LogMessageFormatter.SimulateStructuredLogging(messageBuilder, new object[] { date, "arg0" })();

            formattedMessage.ShouldBe(
                string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd} {1} {0:yyyy}", date, "arg0"));
        }
コード例 #22
0
        public void When_argument_has_format_Then_should_preserve_format()
        {
            var           date           = DateTime.Today;
            Func <string> messageBuilder = () => "Formatted {date1:yyyy-MM-dd} and not formatted {date2}.";

            var formattedMessage = LogMessageFormatter.SimulateStructuredLogging(messageBuilder, new object[] { date, date })();

            formattedMessage.ShouldBe(
                string.Format(CultureInfo.InvariantCulture, "Formatted {0:yyyy-MM-dd} and not formatted {1}.", date, date));
        }
コード例 #23
0
 public void FormatMessage_should_produce_repeatable_results()
 {
     for (var i = 0; i < 100; i++)
     {
         LogMessageFormatter.FormatMessage("aa{prop}bb", new Dictionary <string, object> {
             { "prop", "_" }
         })
         .Should().BeEquivalentTo("aa_bb");
     }
 }
コード例 #24
0
        public void Should_correctly_format_log_event_message_using_its_properties_and_produce_repeatable_results()
        {
            var @event = new LogEvent(LogLevel.Info, DateTimeOffset.Now, "Hello, {User} {@User_Id}! You have {Unread.Count:D5} messages to read.")
                         .WithProperty("User", "Kontur")
                         .WithProperty("@User_Id", 100500)
                         .WithProperty("Unread.Count", 50);

            for (var i = 0; i < 10; i++)
            {
                LogMessageFormatter.Format(@event).Should().Be("Hello, Kontur 100500! You have 00050 messages to read.");
            }
        }
コード例 #25
0
        public void Should_correctly_format_log_event_without_properties_and_produce_repeatable_results()
        {
            var @event = new LogEvent(LogLevel.Info, DateTimeOffset.Now, "Hello!")
                         .WithProperty("User", "Kontur")
                         .WithProperty("@User_Id", 100500)
                         .WithProperty("Unread.Count", 50);

            for (var i = 0; i < 10; i++)
            {
                LogMessageFormatter.Format(@event).Should().Be("Hello!");
            }
        }
コード例 #26
0
            public bool Log(MvxLogLevel logLevel, Func <string> messageFunc, Exception exception,
                            params object[] formatParameters)
            {
                if (messageFunc == null)
                {
                    return(true);
                }

                messageFunc = LogMessageFormatter.SimulateStructuredLogging(messageFunc, formatParameters);

                Write(logLevel, messageFunc(), exception);
                return(true);
            }
コード例 #27
0
 private static void SynchronizeTree(SynchronizeTreeArgs pipelineArgs)
 {
     try
     {
         PipelineRunner.AssertRun(PipelineNames.SynchronizeTree, pipelineArgs);
     }
     catch (Exception exception)
     {
         LogMessage(
             exception,
             "Sharepoint Provider can't process tree.{1}{0}",
             LogMessageFormatter.FormatIntegrationConfigItemID02(pipelineArgs.Context),
             Environment.NewLine);
     }
 }
コード例 #28
0
        private static void WriteMessage(
            LogLevel logLevel,
            string name,
            Func <string> messageFunc,
            object[] formatParameters,
            Exception exception)
        {
            var formattedMessage = LogMessageFormatter.FormatStructuredMessage(messageFunc(), formatParameters, out _);

            if (exception != null)
            {
                formattedMessage = formattedMessage + " -> " + exception;
            }

            Console.WriteLine("[{0:HH:mm:ss} {1}] {2} {3}", DateTime.UtcNow, logLevel, name, formattedMessage);
        }
コード例 #29
0
        /// <summary>
        /// Create a new case with all available details about the error
        /// </summary>
        private void SubmitNew(FBApi api, Mapping target)
        {
            LogMessageFormatter formatter = new LogMessageFormatter(FirstMessage);
            Dictionary<string, string> args = new Dictionary<string, string>
                            {
                                {"sScoutDescription", Error.Fingerprint},
                                {"sProject", target.Project},
                                {"sArea", target.Area},
                                {"ixPriority", target.Priority.ToString()},
                                {"sTitle", formatter.GetTitle()},
                                {"sVersion", Session.Summary.ApplicationVersion.ToString()},
                                {"sEvent", formatter.GetNewEvent(Error)},
                                {"sTags", formatter.GetTags()},
                            };

            string results = api.Cmd("new", args);

            // TODO: Should check for errors here
            Log.Information(LogCategory, "Completed new issue submission", "Scout Description: {0}\r\nProject: {1}\r\nArea: {2}\r\nRaw result: {3}",Error.Fingerprint, target.Project, target.Area, results);
        }
コード例 #30
0
        public static LoggingEvent TranslateEvent([NotNull] ILogger logger, [NotNull] LogEvent @event, bool useVostokTemplate = false)
        {
            var level   = TranslateLevel(@event.Level);
            var message = useVostokTemplate
                ? LogEventFormatter.Format(@event, Template)
                : LogMessageFormatter.Format(@event);
            var timestamp = @event.Timestamp.UtcDateTime;

            var loggingEvent = new LoggingEvent(typeof(Logger), logger.Repository, logger.Name, level, message, @event.Exception);

            FillProperties(loggingEvent, @event.Properties);

            // (iloktionov): Unfortunately, log4net's LoggingEvent does not have a constructor that allows to pass both structured exception and timestamp.
            // (iloktionov): Constructor with Exception parameter just uses DateTime.UtcNow for timestamp.
            // (iloktionov): Constructor with LoggingEventData only allows to pass exception string instead of exception object.
            // (iloktionov): So we take the first ctor and use some dirty expressions to set timestamp in private LoggingEventData instance.

            timestampSetter?.Invoke(loggingEvent, timestamp);

            return(loggingEvent);
        }
コード例 #31
0
        public void Log(LogEvent @event)
        {
            if (@event is null)
            {
                return;
            }

            if (!IsEnabledFor(@event.Level))
            {
                return;
            }

            var logLevel = ConvertLogLevel(@event.Level);

            var message = settings.UseVostokTemplate
                ? LogEventFormatter.Format(@event, Template)
                : LogMessageFormatter.Format(@event);

            var state = new FormattedLogValues(message, Array.Empty <object>());

            logger.Log(logLevel, NullEventId, state, @event.Exception, MessageFormatter);
        }
コード例 #32
0
        private void ThreadSafeDisplayDefect(string caseId, string projectName, string areaName)
        {
            if (InvokeRequired)
            {
                ThreadSafeDisplayDefectInvoker invoker = ThreadSafeDisplayDefect;
                Invoke(invoker, new object[] { caseId, projectName, areaName });
            }
            else
            {
                try
                {
                    //now add these items to the project selection area.
                    ProjectSelection.Items.Clear();
                    ProjectSelection.DataSource = new List<string>(m_ProjectsAndAreas.Keys); //data source requires a list

                    int lastMessageIndex = m_LogMessages.Count - 1;
                    StringBuilder builder = new StringBuilder();

                    // Use compact formatting of all but the last message
                    for (int i = 0; i < lastMessageIndex; i++)
                    {
                        LogMessageFormatter preludeFormatter = new LogMessageFormatter(m_LogMessages[i]);
                        builder.Append(preludeFormatter.GetLogMessageSummary());
                    }

                    // Skip a line between last "prelude" message and the primary message
                    if (lastMessageIndex > 0)
                        builder.AppendLine();

                    // The primary message is the last of the selected messages
                    LogMessageFormatter formatter = new LogMessageFormatter(m_PrimaryMessage);
                    builder.Append(formatter.GetLogMessageDetails());

                    // Add session details after the primary message
                    builder.AppendLine();
                    builder.AppendFormat("Session Details:\r\n");
                    LogMessageFormatter.AppendDivider(builder);
                    builder.Append(formatter.GetSessionDetails());

                    // This will be applied later, after user editing is done
                    m_SessionIdMessage = formatter.GetSessionIdMessage();

                    // Check the fingerprint of the primary message to determine if
                    // a case for this error already exists in FogBugz            
                    if (string.IsNullOrEmpty(caseId))
                    {
                        // If there is no existing case, check if this session has an
                        // affinity for a particular project (i.e. is there a 
                        // MappingTarget associated with this MappingSource in the config?)
                        // If so, default the project selection accordingly.
                        Mapping target = m_Controller.FindTarget(m_PrimaryMessage.Session);
                        m_Context.Log.Verbose(LogCategory, "No existing case found, user will be able to select project", "The current mapping information for the message is:\r\n{0}", (target == null) ? "(No mapping found)" : target.Project);
                        ProjectSelection.SelectedItem = target == null ? null : target.Project;
                        ProjectSelection.Enabled = true;
                        AreaSelection.Enabled = true;
                        CaseLabel.Tag = null;
                        CaseLabel.Text = "(New Case)";
                        Text = "Create New Case";
                    }
                    else
                    {
                        // If a case already exists, get info about it from FogBugz
                        ProjectSelection.SelectedItem = projectName;
                        ProjectSelection.Enabled = false;

                        AreaSelection.SelectedItem = areaName;
                        AreaSelection.Enabled = false;
                        m_Context.Log.Verbose(LogCategory, "Existing case fond, user will not be able to change project / area", "The current case is in:\r\n {0} {1}", projectName, areaName);

                        CaseLabel.Tag = caseId;
                        CaseLabel.Text = caseId;
                        Text = "Edit Case " + caseId;
                    }

                    TitleTextBox.Text = formatter.GetTitle();
                    TitleTextBox.SelectionStart = 0;
                    TitleTextBox.SelectionLength = 0;
                    TitleTextBox.Enabled = true;

                    DescriptionTextBox.Text = builder.ToString();
                    DescriptionTextBox.SelectionStart = 0;
                    DescriptionTextBox.SelectionLength = 0;
                    DescriptionTextBox.Enabled = true;

                    DescriptionTextBox.Select();
                    DescriptionTextBox.Focus(); //this is what they should edit.

                    ValidateData();
                }
                finally
                {
                    //one way or the other, we're done so the user shouldn't be given the impression we're waiting around.
                    UseWaitCursor = false;
                }
            }
        }
コード例 #33
0
        /// <summary>
        /// Update an existing case
        /// </summary>
        private void SubmitUpdate(FBApi api, string caseId)
        {
            Dictionary<string, string> queryArgs = new Dictionary<string, string>
                                    {
                                        {"q", caseId},
                                        {"cols", "sVersion,tags,events"}
                                    };

            string queryResults = api.Cmd("search", queryArgs);
            Log.Verbose(LogCategory, "Retrieved existing issue information from server", "Query Results:\r\n{0}", queryResults);

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(queryResults);
            XmlNodeList eventList = xml.GetElementsByTagName("s");
            string sessionIdMessage = new LogMessageFormatter(FirstMessage).GetSessionIdMessage();

            // If this case already references this session, we're done
            foreach (XmlNode node in eventList)
            {
                if (node.InnerText.Contains(sessionIdMessage))
                    return;
            }

            LogMessageFormatter formatter = new LogMessageFormatter(FirstMessage);
            Dictionary<string, string> updateArgs = new Dictionary<string, string>
                                 {
                                     {"sScoutDescription", Error.Fingerprint},
                                 };

            // Compare the version of the current session with the session associated with the case.
            // The version in FogBugz is the high watermark (highest version seen to-date).
            // If this session if for a 
            XmlNode versionNode = xml.SelectSingleNode("//sVersion");
            Version previousVersion = new Version(versionNode.InnerText);
            if (Session.Summary.ApplicationVersion > previousVersion)
            {
                // If this is a new version, update the high watermark and write
                // a detailed description.
                updateArgs.Add("sVersion", Session.Summary.ApplicationVersion.ToString());
                updateArgs.Add("sEvent", formatter.GetRecurrenceLaterVersionEvent(Error));
                Log.Verbose(LogCategory, "Updating latest version information on existing issue", "This new instance has a higher version number than any previous occurrence so we'll update the high water mark on the server.\r\nPrevious Version: {0}\r\nThis Version: {1}", previousVersion, Session.Summary.ApplicationVersion);
            }
            else if (Session.Summary.ApplicationVersion == previousVersion)
            {
                // If this is another instance of the same version, write a short update
                updateArgs.Add("sEvent", formatter.GetRecurrenceSameVersionEvent(Error));
            }
            else
            {
                // If the version of this session is earlier, ignore this session.
                Log.Information(LogCategory, "Skipping reporting new occurrence of issue because its from an old version", "This new instance has a lower version number than one or more previous occurrences, so we wont report it.\r\nPrevious Version: {0}\r\nThis Version: {1}", previousVersion, Session.Summary.ApplicationVersion);
                return;
            }

            // We use the "new" command rather than "edit" because FogBugz has the
            // smarts to reactivate closed cases with scout descriptions.
            string results = api.Cmd("new", updateArgs);

            // TODO: Should check for errors here
            Log.Information(LogCategory, "Completed issue update submission", "Scout Description: {0}\r\nRaw result: {1}", Error.Fingerprint, results);
        }