33
44namespace CSharpFinder
55{
6- public class Logger
6+ internal class Logger
77 {
8- private readonly string logFilePath ;
8+ private readonly string _logFilePath ;
9+ private string _callingMethod ;
910
10- public Logger ( string filePath )
11+ internal Logger ( string filePath )
1112 {
12- logFilePath = filePath ;
13- string directory = new FileInfo ( logFilePath ) . Directory . FullName ;
13+ _logFilePath = filePath ;
14+ string directory = new FileInfo ( _logFilePath ) . Directory . FullName ;
1415
1516 // Prüfen ob Verzeichnis existiert
1617 if ( ! Directory . Exists ( directory ) )
@@ -19,25 +20,52 @@ public Logger(string filePath)
1920 }
2021
2122 // Prüfen ob Datei existiert
22- if ( ! File . Exists ( logFilePath ) )
23+ if ( ! File . Exists ( _logFilePath ) )
2324 {
24- File . Create ( logFilePath ) . Close ( ) ;
25+ File . Create ( _logFilePath ) . Close ( ) ;
2526 }
2627 }
2728
28- public void Info ( string message )
29+ internal void Info ( string message )
2930 {
30- using ( StreamWriter sw = File . AppendText ( logFilePath ) )
31+ _callingMethod = GetCallingMethod ( ) ;
32+ using ( StreamWriter sw = File . AppendText ( _logFilePath ) )
3133 {
32- sw . WriteLine ( $ "INFO | { DateTime . Now : dd-MM-yyyy HH:mm:ss} | { message } ") ;
34+ sw . WriteLine ( $ "INFO | { DateTime . Now : dd-MM-yyyy HH:mm:ss} { _callingMethod } { message } ") ;
3335 }
3436 }
3537
36- public void Error ( string message )
38+ internal void Error ( string message )
3739 {
38- using ( StreamWriter sw = File . AppendText ( logFilePath ) )
40+ _callingMethod = GetCallingMethod ( ) ;
41+ using ( StreamWriter sw = File . AppendText ( _logFilePath ) )
3942 {
40- sw . WriteLine ( $ "ERROR | { DateTime . Now : dd-MM-yyyy HH:mm:ss} | { message } ") ;
43+ sw . WriteLine ( $ "ERROR | { DateTime . Now : dd-MM-yyyy HH:mm:ss} { _callingMethod } { message } ") ;
44+ }
45+ }
46+
47+ internal void Error ( string message , Exception exception )
48+ {
49+ _callingMethod = GetCallingMethod ( ) ;
50+ using ( StreamWriter sw = File . AppendText ( _logFilePath ) )
51+ {
52+ sw . WriteLine ( $ "ERROR | { DateTime . Now : dd-MM-yyyy HH:mm:ss} { _callingMethod } { exception . GetType ( ) } | { message } ") ;
53+ }
54+ }
55+
56+ private string GetCallingMethod ( )
57+ {
58+ try
59+ {
60+ var stackTrace = new System . Diagnostics . StackTrace ( ) ;
61+ var callingFrame = stackTrace . GetFrame ( 2 ) ; // 2, um die aufrufende Methode zu erhalten
62+ var callingMethod = callingFrame . GetMethod ( ) ;
63+ return $ "| { callingMethod . DeclaringType . Name } .{ callingMethod . Name } |";
64+ }
65+ catch ( Exception ex )
66+ {
67+ Error ( "Logger.GetCallingMethod: " + ex . Message , ex ) ;
68+ return " | " ;
4169 }
4270 }
4371 }
0 commit comments