Repository navigation
Expand file tree
/
Copy pathHttpClientTarget.cs
More file actions
915 lines (817 loc) · 38.6 KB
/
Copy pathHttpClientTarget.cs
File metadata and controls
915 lines (817 loc) · 38.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//
// Copyright (c) 2004-2024 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NLog.Config;
using NLog.Layouts;
/// <summary>
/// Sends log events to an HTTP or HTTPS endpoint, with support for batching and compression.
/// </summary>
/// <remarks>
/// Uses the configured <see cref="Layout"/> for converting log events into the HTTP request body.
///
/// This class can also be used as a base class for custom targets that need custom request serialization or HTTP response handling.
/// </remarks>
[Target("HttpClient")]
[Target("Http")]
public class HttpClientTarget : AsyncTaskTarget
{
private static readonly Encoding _utf8Encoding = new UTF8Encoding(false); // No PreAmble BOM
private readonly char[] _reusableEncodingBuffer = new char[40 * 1024]; // Avoid large-object-heap
private readonly StringBuilder _reusableEncodingBuilder = new StringBuilder();
private readonly Stack<MemoryStream> _memoryStreamPool = new Stack<MemoryStream>();
private volatile HttpClient? _httpClient;
private const int _httpClientLifeTimeTicks = 5 * 60 * 1000;
private volatile int _httpClientCreatedTicks = 0;
#if !NETFRAMEWORK || NET471_OR_GREATER
private readonly NLog.Internal.SslCertificateCache _sslCertificateCache = new NLog.Internal.SslCertificateCache();
#endif
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientTarget"/> class with default settings.
/// </summary>
public HttpClientTarget()
{
RetryDelayMilliseconds = 2500; // Delay before retry when transient failures. Ex Rate-Limited responses (e.g. HTTP 429)
}
/// <summary>
/// Gets or sets the EndPoint destination URL for HTTP requests.
/// </summary>
public Layout Url
{
get => _url;
set
{
if (ReferenceEquals(value, _url)) return;
_url = value;
SignalHttpClientReset();
}
}
private Layout _url = Layout.Empty;
/// <summary>
/// Gets or sets the HTTP method used for the request.
/// </summary>
/// <remarks>Default: <see langword="Post"/></remarks>
public string HttpMethod
{
get => _httpMethod.ToString();
set
{
var httpMethod = value?.Trim() ?? string.Empty;
if (string.Equals(httpMethod, nameof(System.Net.Http.HttpMethod.Post), StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(httpMethod))
_httpMethod = System.Net.Http.HttpMethod.Post;
else if (string.Equals(httpMethod, nameof(System.Net.Http.HttpMethod.Get), StringComparison.OrdinalIgnoreCase))
_httpMethod = System.Net.Http.HttpMethod.Get;
else
_httpMethod = new System.Net.Http.HttpMethod(httpMethod.ToUpperInvariant());
}
}
private System.Net.Http.HttpMethod _httpMethod = System.Net.Http.HttpMethod.Post;
/// <summary>
/// Get or sets the content-type header to use for the http-request.
/// </summary>
/// <remarks>Default: <c>application/json</c></remarks>
public string ContentType
{
get => _contentType;
set
{
if (value == _contentType) return;
_contentType = string.IsNullOrWhiteSpace(value) ? "application/json" : value;
var isTextContentType = _contentType.IndexOf("text", StringComparison.OrdinalIgnoreCase) >= 0 || _contentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) >= 0 || _contentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) >= 0;
_contentTypeHeader = new MediaTypeHeaderValue(_contentType) { CharSet = isTextContentType ? _utf8Encoding.WebName : null };
}
}
private string _contentType = "application/json";
private MediaTypeHeaderValue _contentTypeHeader = new MediaTypeHeaderValue("application/json") { CharSet = _utf8Encoding.WebName };
/// <summary>
/// Gets or sets whether HTTP persistent connections (Keep-Alive) are enabled.
/// </summary>
/// <remarks>Default: <see langword="true"/></remarks>
public bool KeepAlive
{
get => _keepAlive;
set
{
if (value == _keepAlive) return;
_keepAlive = value;
SignalHttpClientReset();
}
}
private bool _keepAlive = true;
/// <summary>
/// Get or sets whether to expect http 100-Continue behavior, where the client sends headers and expects the http-server to reply with http-status 100-continue before sending the http-request body.
///
/// This can introduce additional latency for the http-request, especially when http-server does not support the protocol.
/// </summary>
public bool? Expect100Continue
{
get => _expect100Continue;
set
{
if (value == _expect100Continue) return;
_expect100Continue = value;
SignalHttpClientReset();
}
}
private bool? _expect100Continue
#if NETFRAMEWORK
= false
#endif
;
/// <summary>
/// Gets or sets the line ending mode to use when batching log events.
/// </summary>
/// <remarks>Remember to assign <see cref="AsyncTaskTarget.BatchSize"/> to enable batching. Has no effect when using <see cref="BatchAsJsonArray"/> = <see langword="true"/></remarks>
public LineEndingMode LineEnding { get; set; } = LineEndingMode.LF;
/// <summary>
/// Gets or sets whether batched log events are wrapped in a JSON array. (Overrides <see cref="LineEnding"/>)
/// </summary>
/// <remarks>Default: <see langword="false"/> (Remember to assign <see cref="AsyncTaskTarget.BatchSize"/> to enable batching)</remarks>
public bool BatchAsJsonArray { get; set; }
/// <summary>
/// Gets or sets the timeout duration, in seconds, for HTTP requests.
/// </summary>
/// <remarks>Default: <see langword="30"/> secs</remarks>
public int SendTimeoutSeconds
{
get => _sendTimeoutSeconds;
set
{
if (value == _sendTimeoutSeconds) return;
_sendTimeoutSeconds = value;
SignalHttpClientReset();
}
}
private int _sendTimeoutSeconds = 30;
/// <summary>
/// Gets or sets the <see cref="NetworkCredential"/> username used for HTTP authentication.
/// </summary>
/// <remarks>Explicit Empty/Blank String means use default network credentials (NTLM Windows Authentication)</remarks>
public Layout? NetworkUserName
{
get => _networkUserName;
set
{
if (ReferenceEquals(value, _networkUserName)) return;
_networkUserName = value;
SignalHttpClientReset();
}
}
private Layout? _networkUserName;
/// <summary>
/// Gets or sets the <see cref="NetworkCredential"/> password used for HTTP authentication.
/// </summary>
/// <remarks>Empty/Blank String means use default credentials</remarks>
public Layout? NetworkPassword
{
get => _networkPassword;
set
{
if (ReferenceEquals(value, _networkPassword)) return;
_networkPassword = value;
SignalHttpClientReset();
}
}
private Layout? _networkPassword;
#if !NETFRAMEWORK || NET471_OR_GREATER
/// <summary>
/// Gets or sets the file path to a client SSL certificate for mutual TLS (mTLS) authentication.
/// </summary>
public Layout? SslCertificateFile
{
get => _sslCertificateFile;
set
{
if (ReferenceEquals(value, _sslCertificateFile)) return;
_sslCertificateFile = value;
SignalHttpClientReset();
}
}
private Layout? _sslCertificateFile;
/// <summary>
/// Gets or sets the password for the client SSL certificate specified by <see cref="SslCertificateFile"/>.
/// </summary>
public Layout? SslCertificatePassword
{
get => _sslCertificatePassword;
set
{
if (ReferenceEquals(value, _sslCertificatePassword)) return;
_sslCertificatePassword = value;
SignalHttpClientReset();
}
}
private Layout? _sslCertificatePassword;
/// <summary>
/// Gets or sets the thumbprint of a client SSL certificate from <see cref="System.Security.Cryptography.X509Certificates.X509Store"/>
/// Searches CurrentUser first, then LocalMachine. Used when <see cref="SslCertificateFile"/> is not specified.
/// </summary>
public Layout? SslCertificateThumbprint
{
get => _sslCertificateThumbprint;
set
{
if (ReferenceEquals(value, _sslCertificateThumbprint)) return;
_sslCertificateThumbprint = value;
SignalHttpClientReset();
}
}
private Layout? _sslCertificateThumbprint;
#endif
/// <summary>
/// Gets or sets the maximum payload size (in bytes) before batched log events are split into multiple HTTP payloads.
/// </summary>
/// <remarks>Default: <see langword="40960"/> bytes. Remember to assign <see cref="AsyncTaskTarget.BatchSize"/> to enable batching.</remarks>
public int MaxPayloadSizeBytes { get; set; } = 40 * 1024;
/// <summary>
/// Gets or sets the compression mode used for HTTP request payloads. (None / GZip / GZipFast)
/// </summary>
/// <remarks>Default: <see langword="None"/></remarks>
public HttpCompressionType Compress { get; set; }
/// <summary>
/// Gets or sets the collection of header properties to be included in the http-request.
/// </summary>
[ArrayParameter(typeof(TargetPropertyWithContext), "header")]
public IList<TargetPropertyWithContext> Headers { get; set; } = new List<TargetPropertyWithContext>();
/// <summary>
/// Gets or sets the URL of the proxy server used for HTTP requests.
/// </summary>
/// <remarks>Explicit Empty/Blank String means default proxy</remarks>
public Layout? ProxyUrl
{
get => _proxyUrl;
set
{
if (ReferenceEquals(value, _proxyUrl)) return;
_proxyUrl = value;
SignalHttpClientReset();
}
}
private Layout? _proxyUrl;
/// <summary>
/// Gets or sets the username used when authenticating with the proxy server.
/// </summary>
public Layout? ProxyUser
{
get => _proxyUser;
set
{
if (ReferenceEquals(value, _proxyUser)) return;
_proxyUser = value;
SignalHttpClientReset();
}
}
private Layout? _proxyUser;
/// <summary>
/// Gets or sets the password used when authenticating with the proxy server.
/// </summary>
public Layout? ProxyPassword
{
get => _proxyPassword;
set
{
if (ReferenceEquals(value, _proxyPassword)) return;
_proxyPassword = value;
SignalHttpClientReset();
}
}
private Layout? _proxyPassword;
/// <inheritdoc />
protected override void InitializeTarget()
{
if (Url is null || ReferenceEquals(Url, Layout.Empty))
throw new NLogConfigurationException($"{nameof(Url)} layout must be specified for {GetType()}");
string baseUrl = Url?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;
if (!string.IsNullOrWhiteSpace(baseUrl))
{
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var _))
throw new NLogConfigurationException($"Invalid {nameof(Url)} specified for {GetType()}: {baseUrl}");
}
var proxyUrl = ProxyUrl?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;
if (!string.IsNullOrWhiteSpace(proxyUrl))
{
if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out var _))
throw new NLogConfigurationException($"Invalid {nameof(ProxyUrl)} specified for {GetType()}: {proxyUrl}");
}
base.InitializeTarget();
}
/// <inheritdoc />
protected override void CloseTarget()
{
var oldHttpClient = _httpClient;
_httpClient = null;
_httpClientCreatedTicks = 0;
oldHttpClient?.Dispose();
base.CloseTarget();
}
/// <inheritdoc />
protected sealed override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
{
throw new NotSupportedException(); // Never called
}
/// <inheritdoc />
protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken)
{
int startIndex = 0;
while (startIndex < logEvents.Count)
{
IList<LogEventInfo> batch = startIndex == 0
? logEvents
: new LogEventBatch(logEvents, startIndex, logEvents.Count - startIndex);
var output = RentMemoryStream();
MemoryStream? compressed = null;
try
{
int consumed = WriteHttpRequestBody(batch, output);
if (consumed <= 0)
throw new NLogRuntimeException($"{GetType().Name}.WriteHttpRequest must consume at least one LogEventInfo.");
using (var httpContent = CreateHttpContent(output, out compressed))
{
var url = RenderBaseUrl(batch[0]);
await WriteHttpContentAsync(url, httpContent, cancellationToken).ConfigureAwait(false);
}
startIndex += consumed;
}
finally
{
ReturnMemoryStream(output);
if (compressed != null)
{
ReturnMemoryStream(compressed);
}
}
}
}
/// <summary>
/// Writes the HTTP content to the specified URL and processes the HTTP response asynchronously.
/// </summary>
/// <remarks>The default implementation sends the request and validates the HTTP status code. It does not read the response body.</remarks>
/// <param name="url">The URL to which the HTTP content will be sent.</param>
/// <param name="httpContent">The HTTP content to be sent.</param>
/// <param name="cancellationToken">The cancellation token to cancel the operation.</param>
/// <returns>The HTTP status code returned by the server. Throws <see cref="HttpRequestException"/> for transient/retryable HTTP failures.</returns>
protected virtual async Task<HttpStatusCode> WriteHttpContentAsync(Uri url, HttpContent httpContent, CancellationToken cancellationToken)
{
using var httpResponseMessage = await HttpClientSendAsync(url, httpContent, cancellationToken).ConfigureAwait(false);
var httpStatusCode = httpResponseMessage.StatusCode;
try
{
httpResponseMessage.EnsureSuccessStatusCode(); // Throw if not a success code to trigger retry
return httpStatusCode;
}
catch (HttpRequestException ex)
{
NLog.Common.InternalLogger.Error(ex, "{0}: HTTP request returned status code {1} ({2})", this, (int)httpStatusCode, httpStatusCode);
#if NET || NETSTANDARD2_1_OR_GREATER
if (httpStatusCode == HttpStatusCode.TooManyRequests || httpStatusCode == HttpStatusCode.RequestTimeout || ((int)httpStatusCode >= 500 && httpStatusCode != HttpStatusCode.NetworkAuthenticationRequired))
#else
if ((int)httpStatusCode == 429 || httpStatusCode == HttpStatusCode.RequestTimeout || ((int)httpStatusCode >= 500 && (int)httpStatusCode != 511))
#endif
{
// Retry 429 + 408 + 5xx (server errors, typically transient)
throw;
}
if (RetryCount <= 0)
throw; // When no retry configured, then also re-throw the exception for non-transient errors for NLog AsyncContinuation reporting
// Swallow other failures (e.g. 400 Bad Request) without retrying
return httpStatusCode;
}
}
/// <summary>
/// Sends HTTP content to the specified URL and returns the HTTP response without consuming the response body.
/// </summary>
/// <remarks>
/// This method is intended for derived targets that need custom HTTP response handling. Caller owns disposal of the returned <see cref="HttpResponseMessage"/>.
/// </remarks>
/// <param name="url">Override the default <see cref="HttpClient.BaseAddress"/></param>
/// <param name="httpContent">The contents of the HTTP message</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <returns>HTTP response message. The caller owns disposal of the response.</returns>
protected async Task<HttpResponseMessage> HttpClientSendAsync(Uri? url, HttpContent httpContent, CancellationToken cancellationToken)
{
var httpClient = ResetHttpClientIfNeeded(url);
using var httpRequest = new HttpRequestMessage(_httpMethod, string.Empty) { Content = httpContent };
httpRequest.Content.Headers.ContentType = _contentTypeHeader;
var startTickCount = Environment.TickCount;
try
{
var httpResponseMessage = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
NLog.Common.InternalLogger.Debug(
"{0}: HTTP request completed after {1}ms with http-status-code {2}",
this,
unchecked(Environment.TickCount - startTickCount),
(int)httpResponseMessage.StatusCode);
return httpResponseMessage;
}
catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
NLog.Common.InternalLogger.Error(
ex,
"{0}: HTTP request timed out after {1} ms",
this,
unchecked(Environment.TickCount - startTickCount));
if (HttpClientLifeTimeExpired(Environment.TickCount, 30 * 1000))
SignalHttpClientReset();
throw;
}
catch (OperationCanceledException ex)
{
NLog.Common.InternalLogger.Error(
ex,
"{0}: HTTP request cancelled by {1} after {2} ms",
this,
cancellationToken.IsCancellationRequested ? "target cancellation" : "unknown reason",
unchecked(Environment.TickCount - startTickCount));
throw;
}
catch (Exception ex)
{
NLog.Common.InternalLogger.Error(
ex,
"{0}: HTTP request failed before receiving response after {1} ms",
this,
unchecked(Environment.TickCount - startTickCount));
if (HttpClientLifeTimeExpired(Environment.TickCount, 30 * 1000))
SignalHttpClientReset(); // Reset HttpClient immediately on transport-level failures (e.g. DNS failure, network failure) to clear the stale HttpClient TCP connection pool.
throw;
}
}
/// <summary>
/// Writes log events into the HTTP request body.
/// </summary>
/// <remarks>
/// The default implementation renders the configured <see cref="Layout"/> into the request body.
/// Derived targets can override this method to implement endpoint-specific serialization formats (Ex. protobuf).
/// </remarks>
/// <param name="logEvents">The log events to serialize.</param>
/// <param name="output">The destination stream for the serialized HTTP request body. The stream is owned by <see cref="HttpClientTarget"/> and must not be disposed.</param>
/// <returns>The number of log events serialized into the HTTP request body.</returns>
protected virtual int WriteHttpRequestBody(IList<LogEventInfo> logEvents, MemoryStream output)
{
var newlineDelimiter = BatchAsJsonArray ? ", " : LineEnding.NewLineCharacters;
int consumed = 0;
lock (_reusableEncodingBuilder)
{
try
{
var sb = _reusableEncodingBuilder;
sb.Length = 0;
if (BatchAsJsonArray)
sb.Append('[');
for (int i = 0; i < logEvents.Count; i++)
{
if (consumed != 0)
sb.Append(newlineDelimiter);
Layout.Render(logEvents[i], sb);
consumed++;
if (sb.Length >= MaxPayloadSizeBytes)
break;
}
if (BatchAsJsonArray)
sb.Append(']');
EncodePayload(_utf8Encoding, sb, output);
return consumed;
}
finally
{
if (_reusableEncodingBuilder.Length > _reusableEncodingBuffer.Length)
_reusableEncodingBuilder.Remove(0, _reusableEncodingBuilder.Length - 1); // Attempt soft clear that skips Large-Object-Heap (LOH) re-allocation
_reusableEncodingBuilder.Length = 0;
}
}
}
private HttpContent CreateHttpContent(MemoryStream output, out MemoryStream? compressed)
{
compressed = null;
if (Compress == HttpCompressionType.None)
return new ByteArrayContent(output.GetBuffer(), 0, (int)output.Length);
compressed = RentMemoryStream();
using (var gzip = new GZipStream(compressed,
Compress == HttpCompressionType.GZipFast ? CompressionLevel.Fastest : CompressionLevel.Optimal,
leaveOpen: true))
{
output.Position = 0;
output.CopyTo(gzip);
}
var content = new ByteArrayContent(compressed.GetBuffer(), 0, (int)compressed.Length);
content.Headers.ContentEncoding.Add("gzip");
return content;
}
private MemoryStream RentMemoryStream()
{
lock (_memoryStreamPool)
return _memoryStreamPool.Count > 0 ? _memoryStreamPool.Pop() : new MemoryStream(4096);
}
private void ReturnMemoryStream(MemoryStream stream)
{
if (stream.Capacity < 1_000_000)
{
stream.Position = 0;
stream.SetLength(0);
lock (_memoryStreamPool)
_memoryStreamPool.Push(stream);
}
else
{
stream.Dispose();
}
}
private void EncodePayload(Encoding encoder, StringBuilder payload, MemoryStream output)
{
output.Position = 0;
var totalLength = payload.Length;
lock (_reusableEncodingBuffer)
{
if (totalLength < _reusableEncodingBuffer.Length)
{
payload.CopyTo(0, _reusableEncodingBuffer, 0, totalLength);
var maxByteCount = ((encoder.GetMaxByteCount(totalLength) / 4096) + 1) * 4096;
output.SetLength(maxByteCount);
var byteCount = encoder.GetBytes(_reusableEncodingBuffer, 0, totalLength, output.GetBuffer(), 0);
output.SetLength(byteCount);
output.Position = byteCount;
}
else
{
var payloadString = payload.ToString();
var maxByteCount = encoder.GetMaxByteCount(payloadString.Length);
output.SetLength(maxByteCount);
var byteCount = encoder.GetBytes(payloadString, 0, payloadString.Length, output.GetBuffer(), 0);
output.SetLength(byteCount);
output.Position = byteCount;
}
}
}
private Uri RenderBaseUrl(LogEventInfo logEventInfo)
{
var lastRenderedBaseUri = _lastRenderedBaseUri;
var baseUrl = RenderLogEvent(Url, logEventInfo);
if (string.IsNullOrEmpty(baseUrl))
throw new NLogRuntimeException($"Invalid {nameof(Url)} specified for {GetType()}: {baseUrl}");
if (lastRenderedBaseUri != null && string.Equals(lastRenderedBaseUri.Item1, baseUrl, StringComparison.Ordinal))
return lastRenderedBaseUri.Item2;
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var uri))
throw new NLogRuntimeException($"Invalid {nameof(Url)} specified for {GetType()}: {baseUrl}");
_lastRenderedBaseUri = new Tuple<string, Uri>(baseUrl, uri);
return uri;
}
private Tuple<string, Uri>? _lastRenderedBaseUri = null;
private HttpClient ResetHttpClientIfNeeded(Uri? baseUrl)
{
var oldHttpClient = _httpClient;
int nowTickCount = Environment.TickCount;
if (!HttpClientLifeTimeExpired(nowTickCount, _httpClientLifeTimeTicks) && oldHttpClient != null)
{
if (baseUrl is null || oldHttpClient.BaseAddress?.Equals(baseUrl) == true)
return oldHttpClient;
}
// HttpClient is intended to be long-lived, but DNS changes can cause it to fail. Periodically recycle it to mitigate this.
lock (_reusableEncodingBuffer)
{
oldHttpClient = _httpClient;
if (!HttpClientLifeTimeExpired(nowTickCount, _httpClientLifeTimeTicks) && oldHttpClient != null && (baseUrl is null || oldHttpClient.BaseAddress?.Equals(baseUrl) == true))
return oldHttpClient;
_httpClient = null;
oldHttpClient?.Dispose();
_httpClient = oldHttpClient = CreateNewHttpClient(baseUrl);
_httpClientCreatedTicks = nowTickCount;
}
return oldHttpClient;
}
private bool HttpClientLifeTimeExpired(int nowTickCount, int lifetimeTicks)
{
var deltaTicks = nowTickCount - _httpClientCreatedTicks;
return deltaTicks > lifetimeTicks || deltaTicks < -lifetimeTicks;
}
private void SignalHttpClientReset()
{
if (_httpClientCreatedTicks != 0)
NLog.Common.InternalLogger.Debug("{0}: Signal HttpClient reset after config change", this);
lock (_reusableEncodingBuffer)
{
_httpClientCreatedTicks = 0;
}
}
private HttpClient CreateNewHttpClient(Uri? baseUrl)
{
var nullEvent = LogEventInfo.CreateNullEvent();
var baseAddress = baseUrl?.ToString() ?? Url?.Render(nullEvent);
if (_httpClientCreatedTicks == 0)
NLog.Common.InternalLogger.Info("{0}: Creating HttpClient for BaseAddress: {1}", this, baseAddress);
else
NLog.Common.InternalLogger.Debug("{0}: Creating HttpClient for BaseAddress: {1}", this, baseAddress);
if (baseUrl is null)
{
if (!Uri.TryCreate(baseAddress, UriKind.Absolute, out var baseAddressUri))
throw new NLogRuntimeException($"Invalid {nameof(Url)} specified for {GetType()}: {baseAddress}");
baseUrl = baseAddressUri;
}
var handler = new HttpClientHandler();
#if !NETFRAMEWORK || NET471_OR_GREATER
if (SslCertificateFile != null || SslCertificateThumbprint != null)
{
var sslCertificateFile = SslCertificateFile?.Render(nullEvent) ?? string.Empty;
var sslCertificateThumbprint = SslCertificateThumbprint?.Render(nullEvent) ?? string.Empty;
System.Security.Cryptography.X509Certificates.X509Certificate2Collection? clientCertificates = null;
if (!string.IsNullOrEmpty(sslCertificateFile) || !string.IsNullOrEmpty(sslCertificateThumbprint))
{
try
{
var sslCertificatePassword = SslCertificatePassword?.Render(nullEvent) ?? string.Empty;
clientCertificates = _sslCertificateCache.LoadCertificate(sslCertificateFile, sslCertificatePassword, sslCertificateThumbprint);
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(sslCertificateFile))
{
Common.InternalLogger.Error(ex, "{0}: Failed loading SSL certificate", this);
throw new NLogRuntimeException($"{GetType()}: Failed loading SSL certificate", ex);
}
else
{
Common.InternalLogger.Error(ex, "{0}: Failed loading SSL certificate from file: {1}", this, sslCertificateFile);
throw new NLogRuntimeException($"{GetType()}: Failed loading SSL certificate from file: {sslCertificateFile}", ex);
}
}
}
else
{
Common.InternalLogger.Debug("{0}: Skipped loading SSL certificate, because empty value was resolved", this);
}
if (clientCertificates?.Count > 0)
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.AddRange(clientCertificates);
}
handler.ServerCertificateCustomValidationCallback = static (message, certificate, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
return true;
Common.InternalLogger.Warn("SSL certificate errors were encountered when establishing connection to the server: {0}, Certificate: {1}", sslPolicyErrors, certificate);
if (certificate is null)
return false;
return true;
};
}
#endif
var networkUserName = NetworkUserName?.Render(nullEvent)?.Trim() ?? string.Empty;
if (NetworkUserName != null)
{
handler.PreAuthenticate = true; // Authorization header included upfront (instead of waiting for 401-challenge from server) to avoid extra round-trip and latency
if (string.IsNullOrWhiteSpace(networkUserName))
{
handler.Credentials = CredentialCache.DefaultCredentials;
}
else
{
var networkPassword = NetworkPassword?.Render(nullEvent) ?? string.Empty;
handler.Credentials = new NetworkCredential(networkUserName, networkPassword);
}
}
if (ProxyUrl != null)
{
var proxyAddress = ProxyUrl?.Render(nullEvent) ?? string.Empty;
var proxyUser = ProxyUser?.Render(nullEvent) ?? string.Empty;
var proxyPassword = ProxyPassword?.Render(nullEvent) ?? string.Empty;
handler.UseProxy = true;
handler.Proxy = CreateWebProxy(proxyAddress, proxyUser, proxyPassword);
}
else
{
handler.UseProxy = false;
}
handler.MaxConnectionsPerServer = 10; // Avoid connection pressure to protect the user application
var newHttpClient = new HttpClient(handler)
{
BaseAddress = baseUrl,
};
if (SendTimeoutSeconds > 0)
newHttpClient.Timeout = TimeSpan.FromSeconds(SendTimeoutSeconds);
if (!KeepAlive)
newHttpClient.DefaultRequestHeaders.ConnectionClose = true; // Closes TCP connection after each request (Disables HTTP Keep-Alive)
if (Expect100Continue.HasValue)
newHttpClient.DefaultRequestHeaders.ExpectContinue = Expect100Continue.Value;
foreach (var header in Headers)
{
var headerName = header.Name?.Trim();
if (string.IsNullOrEmpty(headerName))
continue;
var headerValue = header.Layout?.Render(nullEvent) ?? string.Empty;
if (string.IsNullOrWhiteSpace(headerValue) && !header.IncludeEmptyValue)
continue;
newHttpClient.DefaultRequestHeaders.TryAddWithoutValidation(headerName, headerValue);
}
return newHttpClient;
}
private IWebProxy? CreateWebProxy(string proxyAddress, string proxyUser, string proxyPassword)
{
if (string.IsNullOrEmpty(proxyAddress))
return WebRequest.DefaultWebProxy;
if (!Uri.TryCreate(proxyAddress, UriKind.Absolute, out var proxyUri))
throw new NLogRuntimeException($"Invalid {nameof(ProxyUrl)} specified for {GetType()}: {proxyAddress}");
var proxy = new WebProxy(proxyUri);
if (string.IsNullOrEmpty(proxyUser))
{
proxy.UseDefaultCredentials = true;
}
else
{
var cred = proxyUser.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
proxy.Credentials = cred.Length == 1
? new NetworkCredential
{ UserName = proxyUser, Password = proxyPassword }
: new NetworkCredential
{
Domain = cred[0],
UserName = cred[1],
Password = proxyPassword
};
}
return proxy;
}
private sealed class LogEventBatch : IList<LogEventInfo>
{
private readonly IList<LogEventInfo> _source;
private readonly int _offset;
public int Count { get; }
public bool IsReadOnly => true;
public LogEventBatch(IList<LogEventInfo> source, int offset, int count)
{
_source = source;
_offset = offset;
Count = count;
}
public LogEventInfo this[int index]
{
get => _source[_offset + index];
set => _source[_offset + index] = value;
}
public int IndexOf(LogEventInfo item)
{
for (int i = 0; i < Count; i++)
{
if (ReferenceEquals(this[i], item))
return i;
}
return -1;
}
public bool Contains(LogEventInfo item) => IndexOf(item) >= 0;
public void CopyTo(LogEventInfo[] array, int arrayIndex)
{
for (int i = 0; i < Count; i++)
array[arrayIndex + i] = this[i];
}
public void Add(LogEventInfo item) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public void Insert(int index, LogEventInfo item) => throw new NotSupportedException();
public bool Remove(LogEventInfo item) => throw new NotSupportedException();
public void RemoveAt(int index) => throw new NotSupportedException();
public IEnumerator<LogEventInfo> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}