1+ using System . Diagnostics ;
2+ using System . Reflection ;
3+ using Intersect . Framework . Reflection ;
4+ using Microsoft . Extensions . Logging ;
5+ using Serilog ;
6+ using Serilog . Core ;
7+ using Serilog . Events ;
8+ using Serilog . Extensions . Logging ;
9+ using ILogger = Microsoft . Extensions . Logging . ILogger ;
10+
11+ namespace Intersect . Framework . Logging ;
12+
13+ public static class LoggerConfigurationExtensions
14+ {
15+ public static ( ILoggerFactory , ILogger ) CreateLoggerForIntersect (
16+ this LoggerConfiguration loggerConfiguration ,
17+ Assembly forAssembly ,
18+ string categoryName ,
19+ LoggingLevelSwitch ? parentLoggingLevelSwitch = null
20+ )
21+ {
22+ var currentProcess = Process . GetCurrentProcess ( ) ;
23+ var processStartTime = currentProcess . StartTime ;
24+ var executableName = Path . GetFileNameWithoutExtension (
25+ currentProcess . MainModule ? . FileName ?? forAssembly . GetName ( ) . Name
26+ ) ;
27+
28+ LoggingLevelSwitch loggingLevelSwitch =
29+ new ( Debugger . IsAttached ? LogEventLevel . Debug : LogEventLevel . Information ) ;
30+
31+ if ( parentLoggingLevelSwitch is not null )
32+ {
33+ parentLoggingLevelSwitch . MinimumLevelChanged +=
34+ ( _ , args ) => loggingLevelSwitch . MinimumLevel = args . NewLevel ;
35+ }
36+
37+ LoggingLevelSwitch errorLevelSwitch = new ( ) ;
38+
39+ var serilogLogger = loggerConfiguration
40+ . MinimumLevel . ControlledBy ( loggingLevelSwitch )
41+ . Enrich . FromLogContext ( )
42+ . WriteTo . Console ( )
43+ . WriteTo . File (
44+ Path . Combine (
45+ "logs" ,
46+ $ "{ executableName } -{ processStartTime : yyyy_MM_dd-HH_mm_ss_fff} .log"
47+ ) ,
48+ rollOnFileSizeLimit : true ,
49+ retainedFileTimeLimit : TimeSpan . FromDays ( 30 )
50+ )
51+ . WriteTo . File (
52+ Path . Combine ( "logs" , $ "errors-{ executableName } .log") ,
53+ levelSwitch : errorLevelSwitch ,
54+ rollOnFileSizeLimit : true ,
55+ retainedFileTimeLimit : TimeSpan . FromDays ( 30 )
56+ )
57+ . CreateLogger ( ) ;
58+
59+ var loggerFactory = new SerilogLoggerFactory ( serilogLogger , dispose : true ) ;
60+ var logger = loggerFactory . CreateLogger ( categoryName ) ;
61+
62+ logger . LogInformation (
63+ "Starting {AssemblyName} v{AssemblyVersion}" ,
64+ forAssembly . GetName ( ) . Name ,
65+ forAssembly . GetMetadataVersion ( )
66+ ) ;
67+
68+ errorLevelSwitch . MinimumLevel = LogEventLevel . Error ;
69+
70+ return ( loggerFactory , logger ) ;
71+ }
72+ }
0 commit comments