Unable to print query using Miniprofiler












1















I have integrated Entity Framework and CodeFirstStoredProc library in my project. I want to log the queries executed by both the libraries. Previously I was using Database.Log delegate provided by EF but as I want to log query from other libraries also, I decided to integrated Miniprofiler for the same.



I used below code to get the query log in result variable:



MiniProfilerEF6.Initialize();
MiniProfiler.StartNew("Test");
using (MiniProfiler.Current.Step("Level 1"))
{
DbConnection spConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
ProfiledDbConnection profileSpConnection = new ProfiledDbConnection(spConnection, MiniProfiler.Current);
using (EfDataContext db = new EfDataContext(profileSpConnection))
{
List<Domain.PersonEntity> data = db.Persons.ToList();
}
using (StoredProcedureContext db = new StoredProcedureContext(profileSpConnection))
{
List<GetPersonResult> data = db.GetPerson.CallStoredProc(new Domain.GetPersonParameter { IsActive = true }).ToList<GetPersonResult>();
}
string result = MiniProfiler.Current.RenderPlainText();
}
MiniProfiler.Current.Stop();


I expected the output query with all the details but unfortunately I am getting below result:



Manprit-PC at 11/15/2018 2:24:27 PM
Test = ms
> Level 1 = ms (sql = 45ms in 12 cmds)


Am I missing something for the implementation?










share|improve this question



























    1















    I have integrated Entity Framework and CodeFirstStoredProc library in my project. I want to log the queries executed by both the libraries. Previously I was using Database.Log delegate provided by EF but as I want to log query from other libraries also, I decided to integrated Miniprofiler for the same.



    I used below code to get the query log in result variable:



    MiniProfilerEF6.Initialize();
    MiniProfiler.StartNew("Test");
    using (MiniProfiler.Current.Step("Level 1"))
    {
    DbConnection spConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    ProfiledDbConnection profileSpConnection = new ProfiledDbConnection(spConnection, MiniProfiler.Current);
    using (EfDataContext db = new EfDataContext(profileSpConnection))
    {
    List<Domain.PersonEntity> data = db.Persons.ToList();
    }
    using (StoredProcedureContext db = new StoredProcedureContext(profileSpConnection))
    {
    List<GetPersonResult> data = db.GetPerson.CallStoredProc(new Domain.GetPersonParameter { IsActive = true }).ToList<GetPersonResult>();
    }
    string result = MiniProfiler.Current.RenderPlainText();
    }
    MiniProfiler.Current.Stop();


    I expected the output query with all the details but unfortunately I am getting below result:



    Manprit-PC at 11/15/2018 2:24:27 PM
    Test = ms
    > Level 1 = ms (sql = 45ms in 12 cmds)


    Am I missing something for the implementation?










    share|improve this question

























      1












      1








      1








      I have integrated Entity Framework and CodeFirstStoredProc library in my project. I want to log the queries executed by both the libraries. Previously I was using Database.Log delegate provided by EF but as I want to log query from other libraries also, I decided to integrated Miniprofiler for the same.



      I used below code to get the query log in result variable:



      MiniProfilerEF6.Initialize();
      MiniProfiler.StartNew("Test");
      using (MiniProfiler.Current.Step("Level 1"))
      {
      DbConnection spConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
      ProfiledDbConnection profileSpConnection = new ProfiledDbConnection(spConnection, MiniProfiler.Current);
      using (EfDataContext db = new EfDataContext(profileSpConnection))
      {
      List<Domain.PersonEntity> data = db.Persons.ToList();
      }
      using (StoredProcedureContext db = new StoredProcedureContext(profileSpConnection))
      {
      List<GetPersonResult> data = db.GetPerson.CallStoredProc(new Domain.GetPersonParameter { IsActive = true }).ToList<GetPersonResult>();
      }
      string result = MiniProfiler.Current.RenderPlainText();
      }
      MiniProfiler.Current.Stop();


      I expected the output query with all the details but unfortunately I am getting below result:



      Manprit-PC at 11/15/2018 2:24:27 PM
      Test = ms
      > Level 1 = ms (sql = 45ms in 12 cmds)


      Am I missing something for the implementation?










      share|improve this question














      I have integrated Entity Framework and CodeFirstStoredProc library in my project. I want to log the queries executed by both the libraries. Previously I was using Database.Log delegate provided by EF but as I want to log query from other libraries also, I decided to integrated Miniprofiler for the same.



      I used below code to get the query log in result variable:



      MiniProfilerEF6.Initialize();
      MiniProfiler.StartNew("Test");
      using (MiniProfiler.Current.Step("Level 1"))
      {
      DbConnection spConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
      ProfiledDbConnection profileSpConnection = new ProfiledDbConnection(spConnection, MiniProfiler.Current);
      using (EfDataContext db = new EfDataContext(profileSpConnection))
      {
      List<Domain.PersonEntity> data = db.Persons.ToList();
      }
      using (StoredProcedureContext db = new StoredProcedureContext(profileSpConnection))
      {
      List<GetPersonResult> data = db.GetPerson.CallStoredProc(new Domain.GetPersonParameter { IsActive = true }).ToList<GetPersonResult>();
      }
      string result = MiniProfiler.Current.RenderPlainText();
      }
      MiniProfiler.Current.Stop();


      I expected the output query with all the details but unfortunately I am getting below result:



      Manprit-PC at 11/15/2018 2:24:27 PM
      Test = ms
      > Level 1 = ms (sql = 45ms in 12 cmds)


      Am I missing something for the implementation?







      c# .net mvc-mini-profiler miniprofiler






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 15 '18 at 14:28









      Manprit Singh SahotaManprit Singh Sahota

      5451418




      5451418
























          2 Answers
          2






          active

          oldest

          votes


















          1














          This is just how current version of MiniProfilerExtensions.RenderPlainText() renders custom timing information. Custom timings are created using CustomTiming() rather then Step(), they typically are sort of leaf measurements in a MiniProfiler hierarchy such as database interaction or HTTP requests.



          You can easily customize rendering process and render verbose information about custom timings:



          SERVER at 23.11.2018 09:00:00
          MiniProfiler = 48,3[ms]
          > Foo = 35,6ms (sql = 24,8[ms] in 1 cmd) (http = 4,7[ms] in 1 cmd)
          sql 24,8[ms] +16,9[ms] SELECT * FROM Foo
          http 4,7[ms] +41,8[ms] GET http://foo.bar


          Example implementation:



          using StackExchange.Profiling;
          using StackExchange.Profiling.Internal;
          ...
          public static string CustomRenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
          {
          if (profiler == null) return string.Empty;

          var text = StringBuilderCache.Get()
          .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
          .Append(" at ")
          .Append(DateTime.UtcNow)
          .AppendLine();

          var timings = new Stack<Timing>();
          timings.Push(profiler.Root);

          while (timings.Count > 0)
          {
          var timing = timings.Pop();

          text.AppendFormat("{0} {1} = {2:###,##0.##}[ms]",
          new string('>', timing.Depth),
          htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
          timing.DurationMilliseconds);

          if (timing.HasCustomTimings)
          {
          // TODO: Customize this code block.

          // Custom timings grouped by category. Collect all custom timings in a list.
          var customTimingsFlat = new List<KeyValuePair<string, CustomTiming>>(capacity: timing.CustomTimings.Sum(ct => ct.Value.Count));
          foreach (var pair in timing.CustomTimings)
          {
          var type = pair.Key;
          var customTimings = pair.Value;

          customTimingsFlat.AddRange(pair.Value.Select(ct => KeyValuePair.Create(type, ct)));
          text.AppendFormat(" ({0} = {1:###,##0.##}[ms] in {2} cmd{3})",
          type,
          customTimings.Sum(ct => ct.DurationMilliseconds),
          customTimings.Count,
          customTimings.Count == 1 ? string.Empty : "s");
          }

          foreach (var pair in customTimingsFlat.OrderBy(kvp => kvp.Value.StartMilliseconds))
          {
          var type = pair.Key;
          var ct = pair.Value;

          text.AppendLine();
          var mainPart = string.Format("{0}{1} {2:###,##0.##}[ms] +{3:###,##0.##}[ms] ",
          new string(' ', timing.Depth + 2),
          type,
          ct.DurationMilliseconds,
          ct.StartMilliseconds);
          text.Append(mainPart);
          // Shift command text to closer to the command for better readability.
          var prefix = new string(' ', mainPart.Length);
          string cmdLine = null;
          using (var reader = new StringReader(ct.CommandString))
          {
          while ((cmdLine = reader.ReadLine()) != null)
          {
          text.Append(cmdLine);
          if (reader.Peek() == -1 && profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
          {
          break;
          }
          text.AppendLine();
          text.Append(prefix);
          }
          }

          if (profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
          {
          continue;
          }
          text.Append(ct.StackTraceSnippet);
          }
          }

          text.AppendLine();

          if (timing.HasChildren)
          {
          var children = timing.Children;
          for (var i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
          }
          }

          return text.ToStringRecycle();
          }


          Also note that by default in order to render MiniProfiler report with all timings you need to call Stop() first. You can customize this too by calculating timings so far in a report.






          share|improve this answer

































            0














            When profiling EntityFramework 6, you need to hook things up before the first query. So that .Initialize() call needs to happen much earlier, when your application starts up. You can find the MiniProfiler EF6 docs here



            Given the tags, it looks like you're in a web application, so it should happen early like this:



            using StackExchange.Profiling.EntityFramework6;

            protected void Application_Start()
            {
            MiniProfilerEF6.Initialize();
            }





            share|improve this answer
























            • ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

              – Manprit Singh Sahota
              Nov 19 '18 at 6:53











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321634%2funable-to-print-query-using-miniprofiler%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            This is just how current version of MiniProfilerExtensions.RenderPlainText() renders custom timing information. Custom timings are created using CustomTiming() rather then Step(), they typically are sort of leaf measurements in a MiniProfiler hierarchy such as database interaction or HTTP requests.



            You can easily customize rendering process and render verbose information about custom timings:



            SERVER at 23.11.2018 09:00:00
            MiniProfiler = 48,3[ms]
            > Foo = 35,6ms (sql = 24,8[ms] in 1 cmd) (http = 4,7[ms] in 1 cmd)
            sql 24,8[ms] +16,9[ms] SELECT * FROM Foo
            http 4,7[ms] +41,8[ms] GET http://foo.bar


            Example implementation:



            using StackExchange.Profiling;
            using StackExchange.Profiling.Internal;
            ...
            public static string CustomRenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
            {
            if (profiler == null) return string.Empty;

            var text = StringBuilderCache.Get()
            .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
            .Append(" at ")
            .Append(DateTime.UtcNow)
            .AppendLine();

            var timings = new Stack<Timing>();
            timings.Push(profiler.Root);

            while (timings.Count > 0)
            {
            var timing = timings.Pop();

            text.AppendFormat("{0} {1} = {2:###,##0.##}[ms]",
            new string('>', timing.Depth),
            htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
            timing.DurationMilliseconds);

            if (timing.HasCustomTimings)
            {
            // TODO: Customize this code block.

            // Custom timings grouped by category. Collect all custom timings in a list.
            var customTimingsFlat = new List<KeyValuePair<string, CustomTiming>>(capacity: timing.CustomTimings.Sum(ct => ct.Value.Count));
            foreach (var pair in timing.CustomTimings)
            {
            var type = pair.Key;
            var customTimings = pair.Value;

            customTimingsFlat.AddRange(pair.Value.Select(ct => KeyValuePair.Create(type, ct)));
            text.AppendFormat(" ({0} = {1:###,##0.##}[ms] in {2} cmd{3})",
            type,
            customTimings.Sum(ct => ct.DurationMilliseconds),
            customTimings.Count,
            customTimings.Count == 1 ? string.Empty : "s");
            }

            foreach (var pair in customTimingsFlat.OrderBy(kvp => kvp.Value.StartMilliseconds))
            {
            var type = pair.Key;
            var ct = pair.Value;

            text.AppendLine();
            var mainPart = string.Format("{0}{1} {2:###,##0.##}[ms] +{3:###,##0.##}[ms] ",
            new string(' ', timing.Depth + 2),
            type,
            ct.DurationMilliseconds,
            ct.StartMilliseconds);
            text.Append(mainPart);
            // Shift command text to closer to the command for better readability.
            var prefix = new string(' ', mainPart.Length);
            string cmdLine = null;
            using (var reader = new StringReader(ct.CommandString))
            {
            while ((cmdLine = reader.ReadLine()) != null)
            {
            text.Append(cmdLine);
            if (reader.Peek() == -1 && profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
            {
            break;
            }
            text.AppendLine();
            text.Append(prefix);
            }
            }

            if (profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
            {
            continue;
            }
            text.Append(ct.StackTraceSnippet);
            }
            }

            text.AppendLine();

            if (timing.HasChildren)
            {
            var children = timing.Children;
            for (var i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
            }
            }

            return text.ToStringRecycle();
            }


            Also note that by default in order to render MiniProfiler report with all timings you need to call Stop() first. You can customize this too by calculating timings so far in a report.






            share|improve this answer






























              1














              This is just how current version of MiniProfilerExtensions.RenderPlainText() renders custom timing information. Custom timings are created using CustomTiming() rather then Step(), they typically are sort of leaf measurements in a MiniProfiler hierarchy such as database interaction or HTTP requests.



              You can easily customize rendering process and render verbose information about custom timings:



              SERVER at 23.11.2018 09:00:00
              MiniProfiler = 48,3[ms]
              > Foo = 35,6ms (sql = 24,8[ms] in 1 cmd) (http = 4,7[ms] in 1 cmd)
              sql 24,8[ms] +16,9[ms] SELECT * FROM Foo
              http 4,7[ms] +41,8[ms] GET http://foo.bar


              Example implementation:



              using StackExchange.Profiling;
              using StackExchange.Profiling.Internal;
              ...
              public static string CustomRenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
              {
              if (profiler == null) return string.Empty;

              var text = StringBuilderCache.Get()
              .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
              .Append(" at ")
              .Append(DateTime.UtcNow)
              .AppendLine();

              var timings = new Stack<Timing>();
              timings.Push(profiler.Root);

              while (timings.Count > 0)
              {
              var timing = timings.Pop();

              text.AppendFormat("{0} {1} = {2:###,##0.##}[ms]",
              new string('>', timing.Depth),
              htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
              timing.DurationMilliseconds);

              if (timing.HasCustomTimings)
              {
              // TODO: Customize this code block.

              // Custom timings grouped by category. Collect all custom timings in a list.
              var customTimingsFlat = new List<KeyValuePair<string, CustomTiming>>(capacity: timing.CustomTimings.Sum(ct => ct.Value.Count));
              foreach (var pair in timing.CustomTimings)
              {
              var type = pair.Key;
              var customTimings = pair.Value;

              customTimingsFlat.AddRange(pair.Value.Select(ct => KeyValuePair.Create(type, ct)));
              text.AppendFormat(" ({0} = {1:###,##0.##}[ms] in {2} cmd{3})",
              type,
              customTimings.Sum(ct => ct.DurationMilliseconds),
              customTimings.Count,
              customTimings.Count == 1 ? string.Empty : "s");
              }

              foreach (var pair in customTimingsFlat.OrderBy(kvp => kvp.Value.StartMilliseconds))
              {
              var type = pair.Key;
              var ct = pair.Value;

              text.AppendLine();
              var mainPart = string.Format("{0}{1} {2:###,##0.##}[ms] +{3:###,##0.##}[ms] ",
              new string(' ', timing.Depth + 2),
              type,
              ct.DurationMilliseconds,
              ct.StartMilliseconds);
              text.Append(mainPart);
              // Shift command text to closer to the command for better readability.
              var prefix = new string(' ', mainPart.Length);
              string cmdLine = null;
              using (var reader = new StringReader(ct.CommandString))
              {
              while ((cmdLine = reader.ReadLine()) != null)
              {
              text.Append(cmdLine);
              if (reader.Peek() == -1 && profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
              {
              break;
              }
              text.AppendLine();
              text.Append(prefix);
              }
              }

              if (profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
              {
              continue;
              }
              text.Append(ct.StackTraceSnippet);
              }
              }

              text.AppendLine();

              if (timing.HasChildren)
              {
              var children = timing.Children;
              for (var i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
              }
              }

              return text.ToStringRecycle();
              }


              Also note that by default in order to render MiniProfiler report with all timings you need to call Stop() first. You can customize this too by calculating timings so far in a report.






              share|improve this answer




























                1












                1








                1







                This is just how current version of MiniProfilerExtensions.RenderPlainText() renders custom timing information. Custom timings are created using CustomTiming() rather then Step(), they typically are sort of leaf measurements in a MiniProfiler hierarchy such as database interaction or HTTP requests.



                You can easily customize rendering process and render verbose information about custom timings:



                SERVER at 23.11.2018 09:00:00
                MiniProfiler = 48,3[ms]
                > Foo = 35,6ms (sql = 24,8[ms] in 1 cmd) (http = 4,7[ms] in 1 cmd)
                sql 24,8[ms] +16,9[ms] SELECT * FROM Foo
                http 4,7[ms] +41,8[ms] GET http://foo.bar


                Example implementation:



                using StackExchange.Profiling;
                using StackExchange.Profiling.Internal;
                ...
                public static string CustomRenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
                {
                if (profiler == null) return string.Empty;

                var text = StringBuilderCache.Get()
                .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
                .Append(" at ")
                .Append(DateTime.UtcNow)
                .AppendLine();

                var timings = new Stack<Timing>();
                timings.Push(profiler.Root);

                while (timings.Count > 0)
                {
                var timing = timings.Pop();

                text.AppendFormat("{0} {1} = {2:###,##0.##}[ms]",
                new string('>', timing.Depth),
                htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
                timing.DurationMilliseconds);

                if (timing.HasCustomTimings)
                {
                // TODO: Customize this code block.

                // Custom timings grouped by category. Collect all custom timings in a list.
                var customTimingsFlat = new List<KeyValuePair<string, CustomTiming>>(capacity: timing.CustomTimings.Sum(ct => ct.Value.Count));
                foreach (var pair in timing.CustomTimings)
                {
                var type = pair.Key;
                var customTimings = pair.Value;

                customTimingsFlat.AddRange(pair.Value.Select(ct => KeyValuePair.Create(type, ct)));
                text.AppendFormat(" ({0} = {1:###,##0.##}[ms] in {2} cmd{3})",
                type,
                customTimings.Sum(ct => ct.DurationMilliseconds),
                customTimings.Count,
                customTimings.Count == 1 ? string.Empty : "s");
                }

                foreach (var pair in customTimingsFlat.OrderBy(kvp => kvp.Value.StartMilliseconds))
                {
                var type = pair.Key;
                var ct = pair.Value;

                text.AppendLine();
                var mainPart = string.Format("{0}{1} {2:###,##0.##}[ms] +{3:###,##0.##}[ms] ",
                new string(' ', timing.Depth + 2),
                type,
                ct.DurationMilliseconds,
                ct.StartMilliseconds);
                text.Append(mainPart);
                // Shift command text to closer to the command for better readability.
                var prefix = new string(' ', mainPart.Length);
                string cmdLine = null;
                using (var reader = new StringReader(ct.CommandString))
                {
                while ((cmdLine = reader.ReadLine()) != null)
                {
                text.Append(cmdLine);
                if (reader.Peek() == -1 && profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
                {
                break;
                }
                text.AppendLine();
                text.Append(prefix);
                }
                }

                if (profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
                {
                continue;
                }
                text.Append(ct.StackTraceSnippet);
                }
                }

                text.AppendLine();

                if (timing.HasChildren)
                {
                var children = timing.Children;
                for (var i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
                }
                }

                return text.ToStringRecycle();
                }


                Also note that by default in order to render MiniProfiler report with all timings you need to call Stop() first. You can customize this too by calculating timings so far in a report.






                share|improve this answer















                This is just how current version of MiniProfilerExtensions.RenderPlainText() renders custom timing information. Custom timings are created using CustomTiming() rather then Step(), they typically are sort of leaf measurements in a MiniProfiler hierarchy such as database interaction or HTTP requests.



                You can easily customize rendering process and render verbose information about custom timings:



                SERVER at 23.11.2018 09:00:00
                MiniProfiler = 48,3[ms]
                > Foo = 35,6ms (sql = 24,8[ms] in 1 cmd) (http = 4,7[ms] in 1 cmd)
                sql 24,8[ms] +16,9[ms] SELECT * FROM Foo
                http 4,7[ms] +41,8[ms] GET http://foo.bar


                Example implementation:



                using StackExchange.Profiling;
                using StackExchange.Profiling.Internal;
                ...
                public static string CustomRenderPlainText(this MiniProfiler profiler, bool htmlEncode = false)
                {
                if (profiler == null) return string.Empty;

                var text = StringBuilderCache.Get()
                .Append(htmlEncode ? WebUtility.HtmlEncode(Environment.MachineName) : Environment.MachineName)
                .Append(" at ")
                .Append(DateTime.UtcNow)
                .AppendLine();

                var timings = new Stack<Timing>();
                timings.Push(profiler.Root);

                while (timings.Count > 0)
                {
                var timing = timings.Pop();

                text.AppendFormat("{0} {1} = {2:###,##0.##}[ms]",
                new string('>', timing.Depth),
                htmlEncode ? WebUtility.HtmlEncode(timing.Name) : timing.Name,
                timing.DurationMilliseconds);

                if (timing.HasCustomTimings)
                {
                // TODO: Customize this code block.

                // Custom timings grouped by category. Collect all custom timings in a list.
                var customTimingsFlat = new List<KeyValuePair<string, CustomTiming>>(capacity: timing.CustomTimings.Sum(ct => ct.Value.Count));
                foreach (var pair in timing.CustomTimings)
                {
                var type = pair.Key;
                var customTimings = pair.Value;

                customTimingsFlat.AddRange(pair.Value.Select(ct => KeyValuePair.Create(type, ct)));
                text.AppendFormat(" ({0} = {1:###,##0.##}[ms] in {2} cmd{3})",
                type,
                customTimings.Sum(ct => ct.DurationMilliseconds),
                customTimings.Count,
                customTimings.Count == 1 ? string.Empty : "s");
                }

                foreach (var pair in customTimingsFlat.OrderBy(kvp => kvp.Value.StartMilliseconds))
                {
                var type = pair.Key;
                var ct = pair.Value;

                text.AppendLine();
                var mainPart = string.Format("{0}{1} {2:###,##0.##}[ms] +{3:###,##0.##}[ms] ",
                new string(' ', timing.Depth + 2),
                type,
                ct.DurationMilliseconds,
                ct.StartMilliseconds);
                text.Append(mainPart);
                // Shift command text to closer to the command for better readability.
                var prefix = new string(' ', mainPart.Length);
                string cmdLine = null;
                using (var reader = new StringReader(ct.CommandString))
                {
                while ((cmdLine = reader.ReadLine()) != null)
                {
                text.Append(cmdLine);
                if (reader.Peek() == -1 && profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
                {
                break;
                }
                text.AppendLine();
                text.Append(prefix);
                }
                }

                if (profiler.Options.ExcludeStackTraceSnippetFromCustomTimings)
                {
                continue;
                }
                text.Append(ct.StackTraceSnippet);
                }
                }

                text.AppendLine();

                if (timing.HasChildren)
                {
                var children = timing.Children;
                for (var i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
                }
                }

                return text.ToStringRecycle();
                }


                Also note that by default in order to render MiniProfiler report with all timings you need to call Stop() first. You can customize this too by calculating timings so far in a report.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 24 '18 at 8:45

























                answered Nov 23 '18 at 14:46









                Leonid VasilevLeonid Vasilev

                7,09921935




                7,09921935

























                    0














                    When profiling EntityFramework 6, you need to hook things up before the first query. So that .Initialize() call needs to happen much earlier, when your application starts up. You can find the MiniProfiler EF6 docs here



                    Given the tags, it looks like you're in a web application, so it should happen early like this:



                    using StackExchange.Profiling.EntityFramework6;

                    protected void Application_Start()
                    {
                    MiniProfilerEF6.Initialize();
                    }





                    share|improve this answer
























                    • ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                      – Manprit Singh Sahota
                      Nov 19 '18 at 6:53
















                    0














                    When profiling EntityFramework 6, you need to hook things up before the first query. So that .Initialize() call needs to happen much earlier, when your application starts up. You can find the MiniProfiler EF6 docs here



                    Given the tags, it looks like you're in a web application, so it should happen early like this:



                    using StackExchange.Profiling.EntityFramework6;

                    protected void Application_Start()
                    {
                    MiniProfilerEF6.Initialize();
                    }





                    share|improve this answer
























                    • ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                      – Manprit Singh Sahota
                      Nov 19 '18 at 6:53














                    0












                    0








                    0







                    When profiling EntityFramework 6, you need to hook things up before the first query. So that .Initialize() call needs to happen much earlier, when your application starts up. You can find the MiniProfiler EF6 docs here



                    Given the tags, it looks like you're in a web application, so it should happen early like this:



                    using StackExchange.Profiling.EntityFramework6;

                    protected void Application_Start()
                    {
                    MiniProfilerEF6.Initialize();
                    }





                    share|improve this answer













                    When profiling EntityFramework 6, you need to hook things up before the first query. So that .Initialize() call needs to happen much earlier, when your application starts up. You can find the MiniProfiler EF6 docs here



                    Given the tags, it looks like you're in a web application, so it should happen early like this:



                    using StackExchange.Profiling.EntityFramework6;

                    protected void Application_Start()
                    {
                    MiniProfilerEF6.Initialize();
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '18 at 1:17









                    Nick CraverNick Craver

                    530k11511931100




                    530k11511931100













                    • ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                      – Manprit Singh Sahota
                      Nov 19 '18 at 6:53



















                    • ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                      – Manprit Singh Sahota
                      Nov 19 '18 at 6:53

















                    ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                    – Manprit Singh Sahota
                    Nov 19 '18 at 6:53





                    ♦: I am using Console Application and I have already added MiniProfilerEF6.Initialize(); at first line.

                    – Manprit Singh Sahota
                    Nov 19 '18 at 6:53


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321634%2funable-to-print-query-using-miniprofiler%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Sphinx de Gizeh

                    Dijon

                    Équipe cycliste