1+ namespace EasyPicture . Modules
2+ {
3+ public class AuditHandler : IAuditHandler
4+ {
5+ /// <summary>
6+ /// The text file name and location
7+ /// </summary>
8+ public string TextFileName { get ; private set ; }
9+
10+ private readonly bool _audit = false ;
11+ private readonly string _downloadPath ;
12+
13+ private StreamWriter _streamWriter ;
14+
15+ private readonly ILogger _logger ;
16+
17+ /// <summary>
18+ /// Base constructor
19+ /// </summary>
20+ /// <param name="logger"></param>
21+ /// <param name="audit"></param>
22+ /// <param name="auditDirectory"></param>
23+ public AuditHandler (
24+ ILogger logger ,
25+ string auditDirectory ,
26+ bool audit = false )
27+ {
28+ _logger = logger ;
29+ _downloadPath = auditDirectory ;
30+ _audit = audit ;
31+ }
32+
33+ /// <summary>
34+ /// Creates a file based on the name in downloads
35+ /// </summary>
36+ /// <param name="name"></param>
37+ /// <returns></returns>
38+ public async Task CreateFileAsync ( string name , string firstLineAudit = "" )
39+ {
40+ name = name . Replace ( "%20" , "_" ) ;
41+
42+ string auditMessage = $ "{ DateTime . UtcNow } :{ firstLineAudit } ";
43+
44+ if ( _audit )
45+ {
46+ TextFileName = _downloadPath + name + ".txt" ;
47+
48+ await File . WriteAllTextAsync ( TextFileName , $ "{ DateTime . UtcNow } :Audit Started") ;
49+
50+ _streamWriter = new ( TextFileName , append : true ) ;
51+ _streamWriter . AutoFlush = true ;
52+
53+ _logger . LogInformation ( $ "{ DateTime . UtcNow } :Audit Started") ;
54+
55+ if ( ! string . IsNullOrEmpty ( firstLineAudit ) )
56+ {
57+ await _streamWriter . WriteLineAsync ( auditMessage ) ;
58+ }
59+ }
60+ _logger . LogInformation ( auditMessage ) ;
61+ }
62+
63+ /// <summary>
64+ /// Disposes the streamwriter
65+ /// </summary>
66+ /// <returns></returns>
67+ public async Task DropFileStreamAsync ( )
68+ {
69+ if ( _streamWriter != null )
70+ {
71+ await _streamWriter . DisposeAsync ( ) ;
72+ _streamWriter = null ;
73+ }
74+ }
75+
76+ /// <summary>
77+ /// Audits the information message
78+ /// </summary>
79+ /// <param name="auditMessage"></param>
80+ /// <returns></returns>
81+ public async Task AuditInfoMessageAsync ( string auditMessage )
82+ {
83+ string auditMessageConcat = $ "{ DateTime . UtcNow } :{ auditMessage } ";
84+
85+ if ( _audit )
86+ {
87+ try
88+ {
89+ await _streamWriter . WriteLineAsync ( auditMessageConcat ) ;
90+ }
91+ catch ( Exception )
92+ {
93+ _logger . LogWarning ( "Stream was already busy being written to" ) ;
94+ }
95+ }
96+
97+ _logger . LogInformation ( auditMessageConcat ) ;
98+ }
99+
100+ /// <summary>
101+ /// Audits the exception message
102+ /// </summary>
103+ /// <param name="ex"></param>
104+ /// <returns></returns>
105+ public async Task AuditExceptionMessageAsync ( Exception ex )
106+ {
107+ if ( _audit )
108+ {
109+ await AuditInfoMessageAsync ( $ "{ ex . Message } , { ex . InnerException } ") ;
110+ }
111+ _logger . LogError ( ex . Message ) ;
112+ }
113+ }
114+ }
0 commit comments