├── Public.cs ├── packages.config ├── pack.cmd ├── .gitattributes ├── StackTraceFormatter.Source.nuspec ├── StackTraceFormatter.sln ├── StackTraceFormatter.csproj ├── MoreLinq └── MoreEnumerable.Pairwise.cs ├── .gitignore ├── App_Packages └── StackTraceParser │ └── StackTraceParser.cs ├── StackTraceFormatter.cs ├── README.md └── COPYING.txt /Public.cs: -------------------------------------------------------------------------------- 1 | namespace Elmah 2 | { 3 | public partial interface IStackTraceFormatter {} 4 | public partial class StackTraceFormatter {} 5 | public partial class StackTraceHtmlFragments {} 6 | 7 | } -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /pack.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | pushd "%~dp0" 3 | PowerShell -C "(type StackTraceFormatter.cs) -replace 'namespace\s+[a-z]+', 'namespace $rootnamespace$' | Out-File -Encoding ascii StackTraceFormatter.cs.pp" ^ 4 | && call build ^ 5 | && nuget pack StackTraceFormatter.Source.nuspec 6 | popd 7 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /StackTraceFormatter.Source.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StackTraceFormatter.Source 5 | 1.1.0 6 | StackTraceFormatter (C# Source) 7 | Atif Aziz 8 | Atif Aziz 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | https://github.com/atifaziz/StackTraceFormatter 11 | false 12 | Copyright © 2011 Atif Aziz. All rights reserved. 13 | Formatter for .NET and Mono stack traces. 14 | en-US 15 | stack trace formatter diagnostics exception 16 | Bug fix release. See issue #2 (https://github.com/atifaziz/StackTraceFormatter/issues/2) for more information. 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /StackTraceFormatter.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StackTraceFormatter", "StackTraceFormatter.csproj", "{4658EDD5-D30A-44EB-9CA5-8E43F83481D6}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1203CAD6-C000-4078-B298-1D317AD19165}" 9 | ProjectSection(SolutionItems) = preProject 10 | build.cmd = build.cmd 11 | COPYING.txt = COPYING.txt 12 | pack.cmd = pack.cmd 13 | README.md = README.md 14 | StackTraceFormatter.Source.nuspec = StackTraceFormatter.Source.nuspec 15 | EndProjectSection 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {4658EDD5-D30A-44EB-9CA5-8E43F83481D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {4658EDD5-D30A-44EB-9CA5-8E43F83481D6}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {4658EDD5-D30A-44EB-9CA5-8E43F83481D6}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {4658EDD5-D30A-44EB-9CA5-8E43F83481D6}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(SolutionProperties) = preSolution 29 | HideSolutionNode = FALSE 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /StackTraceFormatter.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4658EDD5-D30A-44EB-9CA5-8E43F83481D6} 8 | Library 9 | Properties 10 | Elmah 11 | StackTraceFormatter 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 60 | -------------------------------------------------------------------------------- /MoreLinq/MoreEnumerable.Pairwise.cs: -------------------------------------------------------------------------------- 1 | #region License and Terms 2 | // MoreLINQ - Extensions to LINQ to Objects 3 | // Copyright (c) 2008 Jonathan Skeet. All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | #endregion 17 | 18 | namespace MoreLinq 19 | { 20 | using System; 21 | using System.Collections.Generic; 22 | using System.Diagnostics; 23 | 24 | static partial class MoreEnumerable 25 | { 26 | /// 27 | /// Returns a sequence resulting from applying a function to each 28 | /// element in the source sequence and its 29 | /// predecessor, with the exception of the first element which is 30 | /// only returned as the predecessor of the second element. 31 | /// 32 | /// The type of the elements of . 33 | /// The type of the element of the returned sequence. 34 | /// The source sequence. 35 | /// A transform function to apply to 36 | /// each pair of sequence. 37 | /// 38 | /// Returns the resulting sequence. 39 | /// 40 | /// 41 | /// This operator uses deferred execution and streams its results. 42 | /// 43 | /// 44 | /// 45 | /// int[] numbers = { 123, 456, 789 }; 46 | /// IEnumerable<int> result = numbers.Pairwise(5, (a, b) => a + b); 47 | /// 48 | /// The result variable, when iterated over, will yield 49 | /// 579 and 1245, in turn. 50 | /// 51 | public static IEnumerable Pairwise(this IEnumerable source, Func resultSelector) 52 | { 53 | if (source == null) throw new ArgumentNullException("source"); 54 | if (resultSelector == null) throw new ArgumentNullException("resultSelector"); 55 | return PairwiseImpl(source, resultSelector); 56 | } 57 | 58 | private static IEnumerable PairwiseImpl(this IEnumerable source, Func resultSelector) 59 | { 60 | Debug.Assert(source != null); 61 | Debug.Assert(resultSelector != null); 62 | 63 | using (var e = source.GetEnumerator()) 64 | { 65 | if (!e.MoveNext()) 66 | yield break; 67 | 68 | var previous = e.Current; 69 | while (e.MoveNext()) 70 | { 71 | yield return resultSelector(previous, e.Current); 72 | previous = e.Current; 73 | } 74 | } 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # Visual Studio 2015 cache/options directory 11 | .vs/ 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Roslyn cache directories 26 | *.ide/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | #NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | sql/ 155 | *.Cache 156 | ClientBin/ 157 | [Ss]tyle[Cc]op.* 158 | ~$* 159 | *~ 160 | *.dbmdl 161 | *.dbproj.schemaview 162 | *.pfx 163 | *.publishsettings 164 | node_modules/ 165 | 166 | # RIA/Silverlight projects 167 | Generated_Code/ 168 | 169 | # Backup & report files from converting an old project file 170 | # to a newer Visual Studio version. Backup files are not needed, 171 | # because we have git ;-) 172 | _UpgradeReport_Files/ 173 | Backup*/ 174 | UpgradeLog*.XML 175 | UpgradeLog*.htm 176 | 177 | # SQL Server files 178 | *.mdf 179 | *.ldf 180 | 181 | # Business Intelligence projects 182 | *.rdl.data 183 | *.bim.layout 184 | *.bim_*.settings 185 | 186 | # Microsoft Fakes 187 | FakesAssemblies/ 188 | 189 | # ========================= 190 | # Operating System Files 191 | # ========================= 192 | 193 | # OSX 194 | # ========================= 195 | 196 | .DS_Store 197 | .AppleDouble 198 | .LSOverride 199 | 200 | # Thumbnails 201 | ._* 202 | 203 | # Files that might appear on external disk 204 | .Spotlight-V100 205 | .Trashes 206 | 207 | # Directories potentially created on remote AFP share 208 | .AppleDB 209 | .AppleDesktop 210 | Network Trash Folder 211 | Temporary Items 212 | .apdisk 213 | 214 | # Windows 215 | # ========================= 216 | 217 | # Windows image file caches 218 | Thumbs.db 219 | ehthumbs.db 220 | 221 | # Folder config file 222 | Desktop.ini 223 | 224 | # Recycle Bin used on file shares 225 | $RECYCLE.BIN/ 226 | 227 | # Windows Installer files 228 | *.cab 229 | *.msi 230 | *.msm 231 | *.msp 232 | 233 | # Windows shortcuts 234 | *.lnk 235 | *.pp 236 | -------------------------------------------------------------------------------- /App_Packages/StackTraceParser/StackTraceParser.cs: -------------------------------------------------------------------------------- 1 | #region Copyright (c) 2011 Atif Aziz. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | #endregion 16 | 17 | // ReSharper disable once CheckNamespace 18 | 19 | namespace Elmah 20 | { 21 | #region Imports 22 | 23 | using System; 24 | using System.Collections.Generic; 25 | using System.Linq; 26 | using System.Text.RegularExpressions; 27 | 28 | #endregion 29 | 30 | // ReSharper disable once PartialTypeWithSinglePart 31 | 32 | partial class StackTraceParser 33 | { 34 | const string Space = @"[\x20\t]"; 35 | const string NotSpace = @"[^\x20\t]"; 36 | 37 | static readonly Regex Regex = new Regex(@" 38 | ^ 39 | " + Space + @"* 40 | \w+ " + Space + @"+ 41 | (? 42 | (? " + NotSpace + @"+ ) \. 43 | (? " + NotSpace + @"+? ) " + Space + @"* 44 | (? \( ( " + Space + @"* \) 45 | | (? .+?) " + Space + @"+ (? .+?) 46 | (, " + Space + @"* (? .+?) " + Space + @"+ (? .+?) )* \) ) ) 47 | ( " + Space + @"+ 48 | ( # Microsoft .NET stack traces 49 | \w+ " + Space + @"+ 50 | (? [a-z] \: .+? ) 51 | \: \w+ " + Space + @"+ 52 | (? [0-9]+ ) \p{P}? 53 | | # Mono stack traces 54 | \[0x[0-9a-f]+\] " + Space + @"+ \w+ " + Space + @"+ 55 | <(? [^>]+ )> 56 | :(? [0-9]+ ) 57 | ) 58 | )? 59 | ) 60 | \s* 61 | $", 62 | RegexOptions.IgnoreCase 63 | | RegexOptions.Multiline 64 | | RegexOptions.ExplicitCapture 65 | | RegexOptions.CultureInvariant 66 | | RegexOptions.IgnorePatternWhitespace 67 | | RegexOptions.Compiled, 68 | // Cap the evaluation time to make it obvious should the expression 69 | // fall into the "catastrophic backtracking" trap due to over 70 | // generalization. 71 | // https://github.com/atifaziz/StackTraceParser/issues/4 72 | TimeSpan.FromSeconds(5)); 73 | 74 | public static IEnumerable Parse( 75 | string text, 76 | Func>, string, string, T> selector) 77 | { 78 | if (selector == null) throw new ArgumentNullException("selector"); 79 | 80 | return Parse(text, (idx, len, txt) => txt, 81 | (t, m) => new { Type = t, Method = m }, 82 | (pt, pn) => new KeyValuePair(pt, pn), 83 | // ReSharper disable once PossibleMultipleEnumeration 84 | (pl, ps) => new { List = pl, Items = ps }, 85 | (fn, ln) => new { File = fn, Line = ln }, 86 | (f, tm, p, fl) => selector(f, tm.Type, tm.Method, p.List, p.Items, fl.File, fl.Line)); 87 | } 88 | 89 | public static IEnumerable Parse( 90 | string text, 91 | Func tokenSelector, 92 | Func methodSelector, 93 | Func parameterSelector, 94 | Func, TParameters> parametersSelector, 95 | Func sourceLocationSelector, 96 | Func selector) 97 | { 98 | if (tokenSelector == null) throw new ArgumentNullException("tokenSelector"); 99 | if (methodSelector == null) throw new ArgumentNullException("methodSelector"); 100 | if (parameterSelector == null) throw new ArgumentNullException("parameterSelector"); 101 | if (parametersSelector == null) throw new ArgumentNullException("parametersSelector"); 102 | if (sourceLocationSelector == null) throw new ArgumentNullException("sourceLocationSelector"); 103 | if (selector == null) throw new ArgumentNullException("selector"); 104 | 105 | return from Match m in Regex.Matches(text) 106 | select m.Groups into groups 107 | let pt = groups["pt"].Captures 108 | let pn = groups["pn"].Captures 109 | select selector(Token(groups["frame"], tokenSelector), 110 | methodSelector( 111 | Token(groups["type"], tokenSelector), 112 | Token(groups["method"], tokenSelector)), 113 | parametersSelector( 114 | Token(groups["params"], tokenSelector), 115 | from i in Enumerable.Range(0, pt.Count) 116 | select parameterSelector(Token(pt[i], tokenSelector), 117 | Token(pn[i], tokenSelector))), 118 | sourceLocationSelector(Token(groups["file"], tokenSelector), 119 | Token(groups["line"], tokenSelector))); 120 | } 121 | 122 | static T Token(Capture capture, Func tokenSelector) 123 | { 124 | return tokenSelector(capture.Index, capture.Length, capture.Value); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /StackTraceFormatter.cs: -------------------------------------------------------------------------------- 1 | #region Copyright (c) 2011 Atif Aziz. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | #endregion 16 | 17 | // ReSharper disable once CheckNamespace 18 | 19 | namespace Elmah 20 | { 21 | using System.Collections.Generic; 22 | using System.Diagnostics; 23 | using System.Linq; 24 | using System.Net; 25 | using MoreLinq; 26 | 27 | partial class StackTraceHtmlFragments : IStackTraceFormatter 28 | { 29 | public string BeforeType { get; set; } 30 | public string AfterType { get; set; } 31 | public string BeforeMethod { get; set; } 32 | public string AfterMethod { get; set; } 33 | public string BeforeParameterType { get; set; } 34 | public string AfterParameterType { get; set; } 35 | public string BeforeParameterName { get; set; } 36 | public string AfterParameterName { get; set; } 37 | public string BeforeFile { get; set; } 38 | public string AfterFile { get; set; } 39 | public string BeforeLine { get; set; } 40 | public string AfterLine { get; set; } 41 | public string BeforeFrame { get; set; } 42 | public string AfterFrame { get; set; } 43 | public string BeforeParameters { get; set; } 44 | public string AfterParameters { get; set; } 45 | 46 | string IStackTraceFormatter.Text(string text) => string.IsNullOrEmpty(text) ? string.Empty : WebUtility.HtmlEncode(text); 47 | string IStackTraceFormatter.Type(string markup) => BeforeType + markup + AfterType; 48 | string IStackTraceFormatter.Method(string markup) => BeforeMethod + markup + AfterMethod; 49 | string IStackTraceFormatter.ParameterType(string markup) => BeforeParameterType + markup + AfterParameterType; 50 | string IStackTraceFormatter.ParameterName(string markup) => BeforeParameterName + markup + AfterParameterName; 51 | string IStackTraceFormatter.File(string markup) => BeforeFile + markup + AfterFile; 52 | string IStackTraceFormatter.Line(string markup) => BeforeLine + markup + AfterLine; 53 | string IStackTraceFormatter.BeforeFrame => BeforeFrame ?? string.Empty; 54 | string IStackTraceFormatter.AfterFrame => AfterFrame ?? string.Empty; 55 | string IStackTraceFormatter.BeforeParameters => BeforeParameters ?? string.Empty; 56 | string IStackTraceFormatter.AfterParameters => AfterParameters ?? string.Empty; 57 | } 58 | 59 | partial interface IStackTraceFormatter 60 | { 61 | T Text (string text); 62 | T Type (T markup); 63 | T Method (T markup); 64 | T ParameterType (T markup); 65 | T ParameterName (T markup); 66 | T File (T markup); 67 | T Line (T markup); 68 | T BeforeFrame { get; } 69 | T AfterFrame { get; } 70 | T BeforeParameters { get; } 71 | T AfterParameters { get; } 72 | } 73 | 74 | static partial class StackTraceFormatter 75 | { 76 | static readonly StackTraceHtmlFragments DefaultStackTraceHtmlFragments = new StackTraceHtmlFragments(); 77 | 78 | public static string FormatHtml(string text, IStackTraceFormatter formatter) 79 | { 80 | return string.Concat(Format(text, formatter ?? DefaultStackTraceHtmlFragments)); 81 | } 82 | 83 | public static IEnumerable Format(string text, IStackTraceFormatter formatter) 84 | { 85 | Debug.Assert(text != null); 86 | 87 | var frames = StackTraceParser.Parse 88 | ( 89 | text, 90 | (idx, len, txt) => new 91 | { 92 | Index = idx, 93 | End = idx + len, 94 | Text = txt, 95 | Markup = formatter.Text(txt), 96 | }, 97 | (t, m) => new 98 | { 99 | Type = new { t.Index, t.End, Markup = formatter.Type(t.Markup) }, 100 | Method = new { m.Index, m.End, Markup = formatter.Method(m.Markup) } 101 | }, 102 | (t, n) => new 103 | { 104 | Type = new { t.Index, t.End, Markup = formatter.ParameterType(t.Markup) }, 105 | Name = new { n.Index, n.End, Markup = formatter.ParameterName(n.Markup) } 106 | }, 107 | (p, ps) => new { List = p, Parameters = ps.ToArray() }, 108 | (f, l) => new 109 | { 110 | File = f.Text.Length > 0 111 | ? new { f.Index, f.End, Markup = formatter.File(f.Markup) } 112 | : null, 113 | Line = l.Text.Length > 0 114 | ? new { l.Index, l.End, Markup = formatter.Line(l.Markup) } 115 | : null, 116 | }, 117 | (f, tm, p, fl) => 118 | from tokens in new[] 119 | { 120 | new[] 121 | { 122 | new { f.Index, End = f.Index, Markup = formatter.BeforeFrame }, 123 | tm.Type, 124 | tm.Method, 125 | new { p.List.Index, End = p.List.Index, Markup = formatter.BeforeParameters }, 126 | }, 127 | from pe in p.Parameters 128 | from e in new[] { pe.Type, pe.Name } 129 | select e, 130 | new[] 131 | { 132 | new { Index = p.List.End, p.List.End, Markup = formatter.AfterParameters }, 133 | fl.File, 134 | fl.Line, 135 | new { Index = f.End, f.End, Markup = formatter.AfterFrame }, 136 | }, 137 | } 138 | from token in tokens 139 | where token != null 140 | select token 141 | ); 142 | 143 | return 144 | from token in Enumerable.Repeat(new { Index = 0, End = 0, Markup = default(T) }, 1) 145 | .Concat(from tokens in frames from token in tokens select token) 146 | .Pairwise((prev, curr) => new { Previous = prev, Current = curr }) 147 | from m in new[] 148 | { 149 | formatter.Text(text.Substring(token.Previous.End, token.Current.Index - token.Previous.End)), 150 | token.Current.Markup, 151 | } 152 | select m; 153 | } 154 | } 155 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stack Trace Formatter 2 | 3 | StackTraceFormatter is a single C# function that can format a stack trace text 4 | output (typically returned by [`Environment.StackTrace`][envst] or 5 | [`Exception.StackTrace`][exst]) with arbitrary markup via the following 6 | interface: 7 | 8 | ```c# 9 | interface IStackTraceFormatter 10 | { 11 | T Text (string text); 12 | T Type (T markup); 13 | T Method (T markup); 14 | T ParameterType (T markup); 15 | T ParameterName (T markup); 16 | T File (T markup); 17 | T Line (T markup); 18 | T BeforeFrame { get; } 19 | T AfterFrame { get; } 20 | T BeforeParameters { get; } 21 | T AfterParameters { get; } 22 | } 23 | ``` 24 | 25 | It is available as a [NuGet *source* package][srcpkg] that directly embeds into 26 | a C# project. 27 | 28 | ## Usage 29 | 30 | `StackTraceFormatter` has a function called `Format` that takes the source 31 | text to parse and an interface that is called back to markup the parsed 32 | elements of a stack trace, like frames and method signatures: 33 | 34 | ```c# 35 | static IEnumerable Format(string text, IStackTraceFormatter formatter) 36 | ``` 37 | 38 | The `Format` function is probably too generic for most applications. If you are 39 | looking to simply markup a stack trace with HTML then you will want to use 40 | `FormatHtml` instead: 41 | 42 | ```c# 43 | static string FormatHtml(string text, IStackTraceFormatter formatter) 44 | ``` 45 | 46 | An implementation of `IStackTraceFormatter`, called 47 | `StackTraceHtmlFragments`, is included and which can be passed as the second 48 | parameter to `FormatHtml`: 49 | 50 | ```c# 51 | class StackTraceHtmlFragments : IStackTraceFormatter 52 | { 53 | public string BeforeType { get; set; } 54 | public string AfterType { get; set; } 55 | public string BeforeMethod { get; set; } 56 | public string AfterMethod { get; set; } 57 | public string BeforeParameterType { get; set; } 58 | public string AfterParameterType { get; set; } 59 | public string BeforeParameterName { get; set; } 60 | public string AfterParameterName { get; set; } 61 | public string BeforeFile { get; set; } 62 | public string AfterFile { get; set; } 63 | public string BeforeLine { get; set; } 64 | public string AfterLine { get; set; } 65 | public string BeforeFrame { get; set; } 66 | public string AfterFrame { get; set; } 67 | public string BeforeParameters { get; set; } 68 | public string AfterParameters { get; set; } 69 | 70 | // Rest of class definition omitted here for brevity... 71 | } 72 | ``` 73 | 74 | `StackTraceHtmlFragments` allows use of [C#'s object initializer syntax][csobjinit] 75 | to conveniently define the HTML to insert literally before and after the 76 | various parsed elements of a stack trace. 77 | 78 | Suppose [`Environment.StackTrace`][envst] returns (produced here by running 79 | `Environment.StackTrace` as an expression in [LINQPad][linqpad]): 80 | 81 | at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) 82 | at System.Environment.get_StackTrace() 83 | at UserQuery.RunUserAuthoredQuery() in c:\Users\johndoe\AppData\Local\Temp\LINQPad\_piwdiese\query_dhwxhm.cs:line 33 84 | at LINQPad.ExecutionModel.ClrQueryRunner.Run() 85 | at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner) 86 | at LINQPad.ExecutionModel.Server.StartQuery(QueryRunner runner) 87 | at LINQPad.ExecutionModel.Server.<>c__DisplayClass36.b__35() 88 | at LINQPad.ExecutionModel.Server.SingleThreadExecuter.Work() 89 | at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 90 | at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 91 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 92 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 93 | at System.Threading.ThreadHelper.ThreadStart() 94 | 95 | You could then markup the frames of the above stack trace in HTML like this: 96 | 97 | ```c# 98 | var html = "
"
 99 |          + StackTraceFormatter.FormatHtml(
100 |              Environment.StackTrace,
101 |              new StackTraceHtmlFragments
102 |              {
103 |                  BeforeFrame = "",
104 |                  AfterFrame  = "",
105 |              })
106 |          + "
"; 107 | ``` 108 | 109 | The content of the `html` string after execution of the above line would be: 110 | 111 | ```html 112 |

113 | at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
114 | at System.Environment.get_StackTrace()
115 | at UserQuery.RunUserAuthoredQuery() in c:\Users\johndoe\AppData\Local\Temp\LINQPad\_piwdiese\query_dhwxhm.cs:line 33
116 | at LINQPad.ExecutionModel.ClrQueryRunner.Run()
117 | at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner)
118 | at LINQPad.ExecutionModel.Server.StartQuery(QueryRunner runner)
119 | at LINQPad.ExecutionModel.Server.<>c__DisplayClass36.<ExecuteClrQuery>b__35()
120 | at LINQPad.ExecutionModel.Server.SingleThreadExecuter.Work()
121 | at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
122 | at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
123 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
124 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
125 | at System.Threading.ThreadHelper.ThreadStart()
126 | ``` 127 | 128 | Note also how the source text is also correctly escaped per HTML rules. 129 | 130 | Here is another example that highlights methods and declaring types and 131 | emphasises parameter names: 132 | 133 | ```c# 134 | var html = "
"
135 |          + StackTraceFormatter.FormatHtml(
136 |              Environment.StackTrace,
137 |              new StackTraceHtmlFragments
138 |              {
139 |                  BeforeType          = "",    // highlight type
140 |                  AfterMethod         = "",   // ...and method
141 |                  BeforeParameterName = "",        // emphasise parameter names
142 |                  AfterParameterName  = "",
143 |              })
144 |          + "
"; 145 | ``` 146 | 147 | And now the `html` variable would read: 148 | 149 | ```html 150 |

151 | at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
152 | at System.Environment.get_StackTrace()
153 | at UserQuery.RunUserAuthoredQuery() in c:\Users\johndoe\AppData\Local\Temp\LINQPad\_piwdiese\query_dhwxhm.cs:line 33
154 | at LINQPad.ExecutionModel.ClrQueryRunner.Run()
155 | at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner)
156 | at LINQPad.ExecutionModel.Server.StartQuery(QueryRunner runner)
157 | at LINQPad.ExecutionModel.Server.<>c__DisplayClass36.<ExecuteClrQuery>b__35()
158 | at LINQPad.ExecutionModel.Server.SingleThreadExecuter.Work()
159 | at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
160 | at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
161 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
162 | at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
163 | at System.Threading.ThreadHelper.ThreadStart()
164 | ``` 165 | 166 | You get the idea! 167 | 168 | ## Background 169 | 170 | `StackTraceFormatter`, together with [StackTraceParser][parser], was born as 171 | part of the [ELMAH][elmah] project and used to [color the stack 172 | traces][elmaheg], as can be seen from the screenshot below: 173 | 174 | ![ELMAH](http://www.hanselman.com/blog/content/binary/Windows-Live-Writer/NuGet-Package-of-the-Week-7---ELMAH-Erro_B9F2/Error_%20System.Web.HttpException%20%5B30158b95-0112-4081-91ab-c5ec7848a12c%5D%20-%20Windows%20Internet%20Explorer%20(74)_2.png) 175 | 176 | See the [`ErrorDetailPage` source code][errdp] from the ELMAH repo for a real 177 | example of [how the output of `StackTraceParser` was used for marking up the 178 | stack trace in HTML][elmaheg]. 179 | 180 | [envst]: https://msdn.microsoft.com/en-us/library/system.environment.stacktrace(v=vs.110).aspx 181 | [exst]: https://msdn.microsoft.com/en-us/library/system.exception.stacktrace(v=vs.110).aspx 182 | [srcpkg]: https://www.nuget.org/packages/StackTraceFormatter.Source 183 | [elmah]: https://elmah.github.io/ 184 | [elmaheg]: https://bitbucket.org/project-elmah/main/src/2a6b0b5916a6b4913ca5af4c22c4e4fc69f1260d/src/Elmah.AspNet/ErrorDetailPage.cs?at=default#ErrorDetailPage.cs-45 185 | [errdp]: https://bitbucket.org/project-elmah/main/src/2a6b0b5916a6b4913ca5af4c22c4e4fc69f1260d/src/Elmah.AspNet/ErrorDetailPage.cs?at=default 186 | [linqpad]: https://www.linqpad.net/ 187 | [parser]: https://github.com/atifaziz/StackTraceParser 188 | [csobjinit]: https://msdn.microsoft.com/en-us/library/bb384062.aspx 189 | -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | --------------------------------------------------------------------------------