86 : IBufferWriter<byte>
87 {
88 encoding ??= Encoding.UTF8;
89
90 var mem = default(IMemoryOwner<byte>);
91 var buf = (IBufferWriter<byte>)writer;
92
93 try
94 {
95
96 if (encoding is not UTF8Encoding)
97 {
98 mem = MemoryPool<byte>.Shared.Rent(65535);
100 }
101
102 using var json = new Utf8JsonWriter(buf, new JsonWriterOptions() { Indented = false });
103
104 try
105 {
106 json.WriteStartObject();
107 json.WriteNumber("id", id);
108 json.WriteString("level", level switch
109 {
110 DiagnosticLevel.Trace => "trace",
111 DiagnosticLevel.Info => "info",
112 DiagnosticLevel.Warning => "warning",
113 DiagnosticLevel.Error => "error",
114 DiagnosticLevel.Fatal => "fatal",
115 _ => throw new NotImplementedException(),
116 });
117
118 json.WriteString("message", message);
119 json.WriteStartArray("args");
120
121
122 foreach (var arg in args)
123 JsonSerializer.Serialize(json, arg, arg?.GetType() ?? typeof(object), JsonSerializerOptions.Default);
124
125 json.WriteEndArray();
126
127 if (location.Path != null ||
128 location.StartLine != 0 ||
129 location.StartColumn != 0 ||
130 location.EndLine != 0 ||
131 location.EndColumn != 0)
132 {
133 json.WriteStartObject("location");
134 json.WriteString("path", location.Path);
135 json.WriteStartArray("position");
136 json.WriteNumberValue(location.StartLine);
137 json.WriteNumberValue(location.StartColumn);
138 json.WriteNumberValue(location.EndLine);
139 json.WriteNumberValue(location.EndColumn);
140 json.WriteEndArray();
141
142 json.WriteEndObject();
143 }
144
145 json.WriteEndObject();
146
147
148 json.Flush();
149
150
151 if (mem != null)
152 {
153
154 var len = Encoding.UTF8.GetCharCount(mem.Memory.Span[..(int)json.BytesCommitted]);
155 using var tmp = MemoryPool<char>.Shared.Rent(len);
156 len = Encoding.UTF8.GetChars(mem.Memory.Span[..len], tmp.Memory.Span);
157
158
159 encoding.GetBytes(tmp.Memory.Span[..len], writer);
160 }
161 }
162 catch (ArgumentOutOfRangeException)
163 {
164
165 }
166 }
167 finally
168 {
169
170 mem?.Dispose();
171 }
172 }