| | | 1 | | using System.Globalization; |
| | | 2 | | |
| | | 3 | | namespace ArturRios.Extensions; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Provides extension methods for Exceptions, including utilities to format an exception into a log line. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class ExceptionExtensions |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Formats exception details into a single log line and outputs a generated trace identifier. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="exception">The exception to format.</param> |
| | | 14 | | /// <param name="traceId">The generated trace identifier associated with this log entry.</param> |
| | | 15 | | /// <returns>A single-line string containing timestamp, trace id, exception type, message and stack trace.</returns> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// Line breaks in the message and the stack trace are written as the two-character escape <c>\n</c>, |
| | | 18 | | /// so the result really is one line. A stack trace spans one line per frame, and a message can carry |
| | | 19 | | /// line breaks taken from untrusted input; written raw, either one split the entry across several |
| | | 20 | | /// lines of a line-oriented log, and a crafted message could forge entries that look genuine. |
| | | 21 | | /// The timestamp is UTC, written as <c>yyyy-MM-dd HH:mm:ss</c> with the invariant culture, so it reads |
| | | 22 | | /// the same whatever the current culture's time separator or calendar. |
| | | 23 | | /// </remarks> |
| | | 24 | | public static string ToLogLine(this Exception exception, out Guid traceId) |
| | | 25 | | { |
| | 34 | 26 | | traceId = Guid.NewGuid(); |
| | | 27 | | |
| | 34 | 28 | | var message = EscapeLineBreaks(exception.Message); |
| | 32 | 29 | | var stackTrace = EscapeLineBreaks(exception.StackTrace ?? "No stack trace available"); |
| | | 30 | | |
| | 32 | 31 | | var timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); |
| | | 32 | | |
| | 32 | 33 | | return |
| | 32 | 34 | | $"{timestamp} | TraceId: {traceId} | Exception: {exception.GetType().Name} | Message: {message} | StackTrace |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Replaces every line break — CR LF, LF, CR, and the Unicode line and paragraph separators — with |
| | | 39 | | /// the literal escape <c>\n</c>. |
| | | 40 | | /// </summary> |
| | | 41 | | private static string EscapeLineBreaks(string value) => |
| | 64 | 42 | | value.Replace("\r\n", "\\n") |
| | 64 | 43 | | .Replace('\r', '\n') |
| | 64 | 44 | | .Replace('\u2028', '\n') |
| | 64 | 45 | | .Replace('\u2029', '\n') |
| | 64 | 46 | | .Replace("\n", "\\n"); |
| | | 47 | | } |