77using NLog . Config ;
88using Polly ;
99using Polly . CircuitBreaker ;
10+ using Polly . Wrap ;
1011
1112namespace NLog . Targets . GraylogHttp
1213{
@@ -15,7 +16,7 @@ public class GraylogHttpTarget : TargetWithContext
1516 {
1617 private HttpClient _httpClient ;
1718 private Uri _requestAddress ;
18- private CircuitBreakerPolicy _policy ;
19+ private PolicyWrap _policy ;
1920
2021 public GraylogHttpTarget ( )
2122 {
@@ -68,13 +69,27 @@ protected override void InitializeTarget()
6869
6970 _httpClient . DefaultRequestHeaders . ExpectContinue = false ; // Expect (100) Continue breaks the graylog server
7071
71- _policy = Policy
72- . Handle < Exception > ( )
72+ var waitAndRetryPolicy = Policy
73+ . Handle < Exception > ( e => ! ( e is BrokenCircuitException ) )
74+ . WaitAndRetry (
75+ 1 ,
76+ attempt => TimeSpan . FromMilliseconds ( 200 ) ,
77+ ( exception , calculatedWaitDuration ) =>
78+ {
79+ InternalLogger . Error ( exception , "GraylogHttp(Name={0}): Graylog server error, the log messages were not sent to the server." , Name ) ;
80+ } ) ;
81+
82+ var circuitBreakerPolicy = Policy
83+ . Handle < Exception > ( e => ! ( e is BrokenCircuitException ) )
7384 . AdvancedCircuitBreaker (
7485 ( double ) FailureThreshold / 100 ,
7586 TimeSpan . FromSeconds ( SamplingDurationSeconds ) ,
7687 MinimumThroughput ,
77- TimeSpan . FromSeconds ( FailureCooldownSeconds ) ) ;
88+ TimeSpan . FromSeconds ( FailureCooldownSeconds ) ,
89+ ( exception , span ) => InternalLogger . Error ( exception , "GraylogHttp(Name={0}): Circuit breaker Open" , Name ) ,
90+ ( ) => InternalLogger . Info ( "GraylogHttp(Name={0}): Circuit breaker Reset" , Name ) ) ;
91+
92+ _policy = Policy . Wrap ( waitAndRetryPolicy , circuitBreakerPolicy ) ;
7893
7994 // Prefix the custom properties with underscore upfront, so we don't have to do it for each log-event
8095 foreach ( TargetPropertyWithContext p in ContextProperties )
@@ -137,7 +152,7 @@ protected override void Write(LogEventInfo logEvent)
137152
138153 try
139154 {
140- _policy . Execute ( ( ) =>
155+ _policy . ExecuteAndCapture ( ( ) =>
141156 {
142157 var content = new StringContent ( messageBuilder . Render ( logEvent . TimeStamp ) , Encoding . UTF8 , "application/json" ) ;
143158 return _httpClient . PostAsync ( _requestAddress , content ) . Result . EnsureSuccessStatusCode ( ) ;
@@ -149,6 +164,15 @@ protected override void Write(LogEventInfo logEvent)
149164 "GraylogHttp(Name={0}): The Graylog server seems to be inaccessible, the log messages were not sent to the server." ,
150165 Name ) ;
151166 }
167+ #pragma warning disable CA1031 // Do not catch general exception types
168+ catch ( Exception ex )
169+ #pragma warning restore CA1031 // Do not catch general exception types
170+ {
171+ InternalLogger . Error (
172+ ex ,
173+ "GraylogHttp(Name={0}): Graylog server error, the log messages were not sent to the server." ,
174+ Name ) ;
175+ }
152176 }
153177
154178 /// <summary>
0 commit comments