tgstation-server  4.4.0
The /tg/station 13 server suite
ServiceCollectionExtensions.cs
Go to the documentation of this file.
1 using Microsoft.Extensions.Configuration;
2 using Microsoft.Extensions.DependencyInjection;
3 using Microsoft.Extensions.Logging;
4 using Serilog;
5 using Serilog.Configuration;
6 using System;
7 using System.Diagnostics;
8 using System.Globalization;
10 
11 namespace Tgstation.Server.Host.Extensions
12 {
17  {
21  public const string SerilogContextTemplate = "(Instance:{Instance}|Job:{Job}|Request:{Request}|User:{User}|Monitor:{Monitor}|Bridge:{Bridge}|Chat:{ChatMessage})";
22 
30  public static IServiceCollection UseStandardConfig<TConfig>(this IServiceCollection serviceCollection, IConfiguration configuration) where TConfig : class
31  {
32  if (serviceCollection == null)
33  throw new ArgumentNullException(nameof(serviceCollection));
34  if (configuration == null)
35  throw new ArgumentNullException(nameof(configuration));
36 
37  const string SectionFieldName = nameof(GeneralConfiguration.Section);
38 
39  var configType = typeof(TConfig);
40  var sectionField = configType.GetField(SectionFieldName);
41  if (sectionField == null)
42  throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "{0} has no {1} field!", configType, SectionFieldName));
43 
44  var stringType = typeof(string);
45  if (sectionField.FieldType != stringType)
46  throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "{0} has invalid {1} field type, must be {2}!", configType, SectionFieldName, stringType));
47 
48  var sectionName = (string)sectionField.GetValue(null);
49 
50  return serviceCollection.Configure<TConfig>(configuration.GetSection(sectionName));
51  }
52 
60  public static IServiceCollection SetupLogging(
61  this IServiceCollection serviceCollection,
62  Action<LoggerConfiguration> configurationAction,
63  Action<LoggerSinkConfiguration> sinkConfigurationAction = null)
64  => serviceCollection.AddLogging(builder =>
65  {
66  builder.ClearProviders();
67 
68  var configuration = new LoggerConfiguration()
69  .MinimumLevel
70  .Verbose();
71 
72  configurationAction?.Invoke(configuration);
73 
74  configuration
75  .Enrich.FromLogContext()
76  .WriteTo
77  .Async(sinkConfiguration =>
78  {
79  sinkConfiguration.Console(
80  outputTemplate: "[{Timestamp:HH:mm:ss}] {Level:w3}: {SourceContext:l} "
81  + SerilogContextTemplate
82  + "{NewLine} {Message:lj}{NewLine}{Exception}");
83  sinkConfigurationAction?.Invoke(sinkConfiguration);
84  });
85 
86  builder.AddSerilog(configuration.CreateLogger(), true);
87 
88  if (Debugger.IsAttached)
89  builder.AddDebug();
90  });
91  }
92 }
const string Section
The key for the Microsoft.Extensions.Configuration.IConfigurationSection the GeneralConfiguration res...