@@ -7,10 +7,12 @@ import 'package:strlog/handlers.dart' show FileHandler, LogFileRotationPolicy;
7
7
8
8
final formatter = TextFormatter .withDefaults ();
9
9
final handler = FileHandler (
10
- LogFileRotationPolicy .periodic (Duration (seconds: 30 )), // each 30seconds
10
+ LogFileRotationPolicy .periodic (Duration (seconds: 30 )), // each 30 seconds
11
11
path: './file_rotation_periodic_example.log' ,
12
12
formatter: formatter.call);
13
- final logger = Logger .detached ()..handler = handler;
13
+ final logger = Logger .detached ()
14
+ ..handler = handler
15
+ ..level = Level .all;
14
16
15
17
Future <void > main () async {
16
18
log.set (logger);
@@ -23,29 +25,40 @@ Future<void> main() async {
23
25
])
24
26
});
25
27
26
- final timer = context.startTimer ('Uploading!' , level: Level .info);
28
+ final uploadingTimer = context.startTimer ('Uploading!' , level: Level .info);
27
29
28
30
// Emulate exponential backoff retry
29
31
final maxAttempts = 5 ;
30
- for (int attempt = 0 ; attempt < maxAttempts; attempt++ ) {
32
+ for (int attempt = 1 ; attempt <= maxAttempts; attempt++ ) {
31
33
try {
32
- await Future <void >.delayed (Duration (seconds: 10 * (attempt + 1 )));
34
+ final attemptTimer = context.withFields ({
35
+ Int ('attempt' , attempt),
36
+ }).startTimer ('Uploading attempt' , level: Level .debug);
37
+
38
+ final waitFor = Duration (seconds: (2.5 * attempt).toInt ());
39
+ await Future <void >.delayed (waitFor);
33
40
34
41
// resolve on the last attempt.
35
- if (attempt != maxAttempts - 1 ) {
36
- context
37
- .error ('Failed to upload, retrying...' , {Int ('attempt' , attempt)});
42
+ if (attempt != maxAttempts) {
43
+ attemptTimer.stop ('Failed attempt' );
44
+ context.warn ('Failed to upload, retrying...' ,
45
+ {Int ('attempt' , attempt), Dur ('waited_for' , waitFor)});
46
+
38
47
throw Exception ('failed' );
39
48
}
40
49
50
+ attemptTimer.stop ('Succeeded' );
51
+
41
52
break ; // Success, exit loop
42
53
} catch (e) {
43
- timer.stop ('Aborting...' );
44
- context.fatal ('Failed to upload!' , {const Str ('reason' , 'Timeout' )});
54
+ if (attempt == maxAttempts) {
55
+ uploadingTimer.stop ('Aborting...' );
56
+ context.error ('Failed to upload!' , {const Str ('reason' , 'Timeout' )});
45
57
46
- if (attempt == maxAttempts - 1 ) rethrow ; // Last attempt failed
58
+ rethrow ; // Last attempt failed
59
+ }
47
60
}
48
-
49
- timer.stop ('Uploaded!' );
50
61
}
62
+
63
+ uploadingTimer.stop ('Uploaded!' );
51
64
}
0 commit comments