1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+
4
+ using Microsoft . DevProxy . Abstractions ;
5
+ using Microsoft . Extensions . Configuration ;
6
+ using Microsoft . Extensions . Logging ;
7
+
8
+ namespace Microsoft . DevProxy . Plugins . Reporters ;
9
+
10
+ public abstract class BaseReporter : BaseProxyPlugin
11
+ {
12
+ public virtual string FileExtension => throw new NotImplementedException ( ) ;
13
+
14
+ public override void Register ( IPluginEvents pluginEvents ,
15
+ IProxyContext context ,
16
+ ISet < UrlToWatch > urlsToWatch ,
17
+ IConfigurationSection ? configSection = null )
18
+ {
19
+ base . Register ( pluginEvents , context , urlsToWatch , configSection ) ;
20
+
21
+ pluginEvents . AfterRecordingStop += AfterRecordingStop ;
22
+ }
23
+
24
+ protected abstract string ? GetReport ( KeyValuePair < string , object > report ) ;
25
+
26
+ protected virtual Task AfterRecordingStop ( object sender , RecordingArgs e )
27
+ {
28
+ if ( ! e . GlobalData . ContainsKey ( ProxyUtils . ReportsKey ) ||
29
+ e . GlobalData [ ProxyUtils . ReportsKey ] is not Dictionary < string , object > reports ||
30
+ ! reports . Any ( ) )
31
+ {
32
+ _logger ? . LogDebug ( "No reports found" ) ;
33
+ return Task . CompletedTask ;
34
+ }
35
+
36
+ foreach ( var report in reports )
37
+ {
38
+ _logger ? . LogDebug ( "Transforming report {reportKey}..." , report . Key ) ;
39
+
40
+ var reportContents = GetReport ( report ) ;
41
+
42
+ if ( string . IsNullOrEmpty ( reportContents ) )
43
+ {
44
+ _logger ? . LogDebug ( "Report {reportKey} is empty, ignore" , report . Key ) ;
45
+ continue ;
46
+ }
47
+
48
+ var fileName = $ "{ report . Key } _{ Name } { FileExtension } ";
49
+ _logger ? . LogDebug ( "File name for report {report}: {fileName}" , report . Key , fileName ) ;
50
+
51
+ if ( File . Exists ( fileName ) )
52
+ {
53
+ _logger ? . LogDebug ( "File {fileName} already exists, appending timestamp" , fileName ) ;
54
+ fileName = $ "{ report . Key } _{ Name } _{ DateTime . Now : yyyyMMddHHmmss} { FileExtension } ";
55
+ }
56
+
57
+ _logger ? . LogDebug ( "Writing report {reportKey} to {fileName}..." , report . Key , fileName ) ;
58
+ File . WriteAllText ( fileName , reportContents ) ;
59
+ }
60
+
61
+ return Task . CompletedTask ;
62
+ }
63
+ }
0 commit comments