Program.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using CommandLine;
  13. using Emby.Server.Implementations;
  14. using Emby.Server.Implementations.IO;
  15. using Jellyfin.Api.Controllers;
  16. using MediaBrowser.Common.Configuration;
  17. using MediaBrowser.Common.Net;
  18. using MediaBrowser.Controller.Extensions;
  19. using Microsoft.AspNetCore.Hosting;
  20. using Microsoft.AspNetCore.Server.Kestrel.Core;
  21. using Microsoft.Extensions.Configuration;
  22. using Microsoft.Extensions.DependencyInjection;
  23. using Microsoft.Extensions.DependencyInjection.Extensions;
  24. using Microsoft.Extensions.Hosting;
  25. using Microsoft.Extensions.Logging;
  26. using Microsoft.Extensions.Logging.Abstractions;
  27. using Serilog;
  28. using Serilog.Extensions.Logging;
  29. using SQLitePCL;
  30. using ConfigurationExtensions = MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  31. using ILogger = Microsoft.Extensions.Logging.ILogger;
  32. namespace Jellyfin.Server
  33. {
  34. /// <summary>
  35. /// Class containing the entry point of the application.
  36. /// </summary>
  37. public static class Program
  38. {
  39. /// <summary>
  40. /// The name of logging configuration file containing application defaults.
  41. /// </summary>
  42. public const string LoggingConfigFileDefault = "logging.default.json";
  43. /// <summary>
  44. /// The name of the logging configuration file containing the system-specific override settings.
  45. /// </summary>
  46. public const string LoggingConfigFileSystem = "logging.json";
  47. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  48. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  49. private static ILogger _logger = NullLogger.Instance;
  50. private static bool _restartOnShutdown;
  51. /// <summary>
  52. /// The entry point of the application.
  53. /// </summary>
  54. /// <param name="args">The command line arguments passed.</param>
  55. /// <returns><see cref="Task" />.</returns>
  56. public static Task Main(string[] args)
  57. {
  58. static Task ErrorParsingArguments(IEnumerable<Error> errors)
  59. {
  60. Environment.ExitCode = 1;
  61. return Task.CompletedTask;
  62. }
  63. // Parse the command line arguments and either start the app or exit indicating error
  64. return Parser.Default.ParseArguments<StartupOptions>(args)
  65. .MapResult(StartApp, ErrorParsingArguments);
  66. }
  67. /// <summary>
  68. /// Shuts down the application.
  69. /// </summary>
  70. internal static void Shutdown()
  71. {
  72. if (!_tokenSource.IsCancellationRequested)
  73. {
  74. _tokenSource.Cancel();
  75. }
  76. }
  77. /// <summary>
  78. /// Restarts the application.
  79. /// </summary>
  80. internal static void Restart()
  81. {
  82. _restartOnShutdown = true;
  83. Shutdown();
  84. }
  85. private static async Task StartApp(StartupOptions options)
  86. {
  87. var stopWatch = new Stopwatch();
  88. stopWatch.Start();
  89. // Log all uncaught exceptions to std error
  90. static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) =>
  91. Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject.ToString());
  92. AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole;
  93. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  94. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  95. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  96. // Enable cl-va P010 interop for tonemapping on Intel VAAPI
  97. Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1");
  98. Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1");
  99. await InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  100. // Create an instance of the application configuration to use for application startup
  101. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  102. // Initialize logging framework
  103. InitializeLoggingFramework(startupConfig, appPaths);
  104. _logger = _loggerFactory.CreateLogger("Main");
  105. // Log uncaught exceptions to the logging instead of std error
  106. AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole;
  107. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  108. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  109. // Intercept Ctrl+C and Ctrl+Break
  110. Console.CancelKeyPress += (sender, e) =>
  111. {
  112. if (_tokenSource.IsCancellationRequested)
  113. {
  114. return; // Already shutting down
  115. }
  116. e.Cancel = true;
  117. _logger.LogInformation("Ctrl+C, shutting down");
  118. Environment.ExitCode = 128 + 2;
  119. Shutdown();
  120. };
  121. // Register a SIGTERM handler
  122. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  123. {
  124. if (_tokenSource.IsCancellationRequested)
  125. {
  126. return; // Already shutting down
  127. }
  128. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  129. Environment.ExitCode = 128 + 15;
  130. Shutdown();
  131. };
  132. _logger.LogInformation(
  133. "Jellyfin version: {Version}",
  134. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  135. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  136. PerformStaticInitialization();
  137. var serviceCollection = new ServiceCollection();
  138. var appHost = new CoreAppHost(
  139. appPaths,
  140. _loggerFactory,
  141. options,
  142. startupConfig,
  143. new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
  144. serviceCollection);
  145. try
  146. {
  147. // If hosting the web client, validate the client content path
  148. if (startupConfig.HostWebClient())
  149. {
  150. string? webContentPath = appHost.ServerConfigurationManager.ApplicationPaths.WebPath;
  151. if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0)
  152. {
  153. throw new InvalidOperationException(
  154. "The server is expected to host the web client, but the provided content directory is either " +
  155. $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " +
  156. "server, you may set the '--nowebclient' command line flag, or set" +
  157. $"'{MediaBrowser.Controller.Extensions.ConfigurationExtensions.HostWebClientKey}=false' in your config settings.");
  158. }
  159. }
  160. appHost.Init();
  161. var webHost = new WebHostBuilder().ConfigureWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build();
  162. // Re-use the web host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  163. appHost.ServiceProvider = webHost.Services;
  164. await appHost.InitializeServices().ConfigureAwait(false);
  165. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  166. try
  167. {
  168. await webHost.StartAsync().ConfigureAwait(false);
  169. }
  170. catch
  171. {
  172. _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in network.xml and try again.");
  173. throw;
  174. }
  175. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  176. stopWatch.Stop();
  177. _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed);
  178. // Block main thread until shutdown
  179. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  180. }
  181. catch (TaskCanceledException)
  182. {
  183. // Don't throw on cancellation
  184. }
  185. catch (Exception ex)
  186. {
  187. _logger.LogCritical(ex, "Error while starting server.");
  188. }
  189. finally
  190. {
  191. appHost?.Dispose();
  192. }
  193. if (_restartOnShutdown)
  194. {
  195. StartNewInstance(options);
  196. }
  197. }
  198. /// <summary>
  199. /// Call static initialization methods for the application.
  200. /// </summary>
  201. public static void PerformStaticInitialization()
  202. {
  203. // Make sure we have all the code pages we can get
  204. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  205. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  206. // Increase the max http request limit
  207. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  208. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  209. // Disable the "Expect: 100-Continue" header by default
  210. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  211. ServicePointManager.Expect100Continue = false;
  212. Batteries_V2.Init();
  213. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  214. {
  215. _logger.LogWarning("Failed to enable shared cache for SQLite");
  216. }
  217. }
  218. /// <summary>
  219. /// Configure the web host builder.
  220. /// </summary>
  221. /// <param name="builder">The builder to configure.</param>
  222. /// <param name="appHost">The application host.</param>
  223. /// <param name="serviceCollection">The application service collection.</param>
  224. /// <param name="commandLineOpts">The command line options passed to the application.</param>
  225. /// <param name="startupConfig">The application configuration.</param>
  226. /// <param name="appPaths">The application paths.</param>
  227. /// <returns>The configured web host builder.</returns>
  228. public static IWebHostBuilder ConfigureWebHostBuilder(
  229. this IWebHostBuilder builder,
  230. ApplicationHost appHost,
  231. IServiceCollection serviceCollection,
  232. StartupOptions commandLineOpts,
  233. IConfiguration startupConfig,
  234. IApplicationPaths appPaths)
  235. {
  236. return builder
  237. .UseKestrel((builderContext, options) =>
  238. {
  239. var addresses = appHost.NetManager.GetAllBindInterfaces();
  240. bool flagged = false;
  241. foreach (IPObject netAdd in addresses)
  242. {
  243. _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd);
  244. options.Listen(netAdd.Address, appHost.HttpPort);
  245. if (appHost.ListenWithHttps)
  246. {
  247. options.Listen(
  248. netAdd.Address,
  249. appHost.HttpsPort,
  250. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  251. }
  252. else if (builderContext.HostingEnvironment.IsDevelopment())
  253. {
  254. try
  255. {
  256. options.Listen(
  257. netAdd.Address,
  258. appHost.HttpsPort,
  259. listenOptions => listenOptions.UseHttps());
  260. }
  261. catch (InvalidOperationException)
  262. {
  263. if (!flagged)
  264. {
  265. _logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted.");
  266. flagged = true;
  267. }
  268. }
  269. }
  270. }
  271. // Bind to unix socket (only on macOS and Linux)
  272. if (startupConfig.UseUnixSocket() && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  273. {
  274. var socketPath = startupConfig.GetUnixSocketPath();
  275. if (string.IsNullOrEmpty(socketPath))
  276. {
  277. var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
  278. if (xdgRuntimeDir == null)
  279. {
  280. // Fall back to config dir
  281. socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, "socket.sock");
  282. }
  283. else
  284. {
  285. socketPath = Path.Join(xdgRuntimeDir, "jellyfin-socket");
  286. }
  287. }
  288. // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
  289. if (File.Exists(socketPath))
  290. {
  291. File.Delete(socketPath);
  292. }
  293. options.ListenUnixSocket(socketPath);
  294. _logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath);
  295. }
  296. })
  297. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(commandLineOpts, appPaths, startupConfig))
  298. .UseSerilog()
  299. .ConfigureServices(services =>
  300. {
  301. // Merge the external ServiceCollection into ASP.NET DI
  302. services.Add(serviceCollection);
  303. })
  304. .UseStartup<Startup>();
  305. }
  306. /// <summary>
  307. /// Create the data, config and log paths from the variety of inputs(command line args,
  308. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  309. /// for everything else the
  310. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  311. /// is followed.
  312. /// </summary>
  313. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  314. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  315. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  316. {
  317. // dataDir
  318. // IF --datadir
  319. // ELSE IF $JELLYFIN_DATA_DIR
  320. // ELSE IF windows, use <%APPDATA%>/jellyfin
  321. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  322. // ELSE use $HOME/.local/share/jellyfin
  323. var dataDir = options.DataDir;
  324. if (string.IsNullOrEmpty(dataDir))
  325. {
  326. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  327. if (string.IsNullOrEmpty(dataDir))
  328. {
  329. // LocalApplicationData follows the XDG spec on unix machines
  330. dataDir = Path.Combine(
  331. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  332. "jellyfin");
  333. }
  334. }
  335. // configDir
  336. // IF --configdir
  337. // ELSE IF $JELLYFIN_CONFIG_DIR
  338. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  339. // ELSE IF <datadir>/config exists, use that
  340. // ELSE IF windows, use <datadir>/config
  341. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  342. // ELSE $HOME/.config/jellyfin
  343. var configDir = options.ConfigDir;
  344. if (string.IsNullOrEmpty(configDir))
  345. {
  346. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  347. if (string.IsNullOrEmpty(configDir))
  348. {
  349. if (options.DataDir != null
  350. || Directory.Exists(Path.Combine(dataDir, "config"))
  351. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  352. {
  353. // Hang config folder off already set dataDir
  354. configDir = Path.Combine(dataDir, "config");
  355. }
  356. else
  357. {
  358. // $XDG_CONFIG_HOME defines the base directory relative to which
  359. // user specific configuration files should be stored.
  360. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  361. // If $XDG_CONFIG_HOME is either not set or empty,
  362. // a default equal to $HOME /.config should be used.
  363. if (string.IsNullOrEmpty(configDir))
  364. {
  365. configDir = Path.Combine(
  366. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  367. ".config");
  368. }
  369. configDir = Path.Combine(configDir, "jellyfin");
  370. }
  371. }
  372. }
  373. // cacheDir
  374. // IF --cachedir
  375. // ELSE IF $JELLYFIN_CACHE_DIR
  376. // ELSE IF windows, use <datadir>/cache
  377. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  378. // ELSE HOME/.cache/jellyfin
  379. var cacheDir = options.CacheDir;
  380. if (string.IsNullOrEmpty(cacheDir))
  381. {
  382. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  383. if (string.IsNullOrEmpty(cacheDir))
  384. {
  385. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  386. {
  387. // Hang cache folder off already set dataDir
  388. cacheDir = Path.Combine(dataDir, "cache");
  389. }
  390. else
  391. {
  392. // $XDG_CACHE_HOME defines the base directory relative to which
  393. // user specific non-essential data files should be stored.
  394. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  395. // If $XDG_CACHE_HOME is either not set or empty,
  396. // a default equal to $HOME/.cache should be used.
  397. if (string.IsNullOrEmpty(cacheDir))
  398. {
  399. cacheDir = Path.Combine(
  400. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  401. ".cache");
  402. }
  403. cacheDir = Path.Combine(cacheDir, "jellyfin");
  404. }
  405. }
  406. }
  407. // webDir
  408. // IF --webdir
  409. // ELSE IF $JELLYFIN_WEB_DIR
  410. // ELSE <bindir>/jellyfin-web
  411. var webDir = options.WebDir;
  412. if (string.IsNullOrEmpty(webDir))
  413. {
  414. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  415. if (string.IsNullOrEmpty(webDir))
  416. {
  417. // Use default location under ResourcesPath
  418. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  419. }
  420. }
  421. // logDir
  422. // IF --logdir
  423. // ELSE IF $JELLYFIN_LOG_DIR
  424. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  425. // ELSE <datadir>/log
  426. var logDir = options.LogDir;
  427. if (string.IsNullOrEmpty(logDir))
  428. {
  429. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  430. if (string.IsNullOrEmpty(logDir))
  431. {
  432. // Hang log folder off already set dataDir
  433. logDir = Path.Combine(dataDir, "log");
  434. }
  435. }
  436. // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
  437. dataDir = Path.GetFullPath(dataDir);
  438. logDir = Path.GetFullPath(logDir);
  439. configDir = Path.GetFullPath(configDir);
  440. cacheDir = Path.GetFullPath(cacheDir);
  441. webDir = Path.GetFullPath(webDir);
  442. // Ensure the main folders exist before we continue
  443. try
  444. {
  445. Directory.CreateDirectory(dataDir);
  446. Directory.CreateDirectory(logDir);
  447. Directory.CreateDirectory(configDir);
  448. Directory.CreateDirectory(cacheDir);
  449. }
  450. catch (IOException ex)
  451. {
  452. Console.Error.WriteLine("Error whilst attempting to create folder");
  453. Console.Error.WriteLine(ex.ToString());
  454. Environment.Exit(1);
  455. }
  456. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  457. }
  458. /// <summary>
  459. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  460. /// already.
  461. /// </summary>
  462. /// <param name="appPaths">The application paths.</param>
  463. /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
  464. public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  465. {
  466. // Do nothing if the config file already exists
  467. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  468. if (File.Exists(configPath))
  469. {
  470. return;
  471. }
  472. // Get a stream of the resource contents
  473. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  474. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  475. await using Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  476. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  477. // Copy the resource contents to the expected file path for the config file
  478. await using Stream dst = File.Open(configPath, FileMode.CreateNew);
  479. await resource.CopyToAsync(dst).ConfigureAwait(false);
  480. }
  481. /// <summary>
  482. /// Create the application configuration.
  483. /// </summary>
  484. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  485. /// <param name="appPaths">The application paths.</param>
  486. /// <returns>The application configuration.</returns>
  487. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  488. {
  489. return new ConfigurationBuilder()
  490. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  491. .Build();
  492. }
  493. private static IConfigurationBuilder ConfigureAppConfiguration(
  494. this IConfigurationBuilder config,
  495. StartupOptions commandLineOpts,
  496. IApplicationPaths appPaths,
  497. IConfiguration? startupConfig = null)
  498. {
  499. // Use the swagger API page as the default redirect path if not hosting the web client
  500. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  501. if (startupConfig != null && !startupConfig.HostWebClient())
  502. {
  503. inMemoryDefaultConfig[ConfigurationExtensions.DefaultRedirectKey] = "api-docs/swagger";
  504. }
  505. return config
  506. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  507. .AddInMemoryCollection(inMemoryDefaultConfig)
  508. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  509. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  510. .AddEnvironmentVariables("JELLYFIN_")
  511. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  512. }
  513. /// <summary>
  514. /// Initialize Serilog using configuration and fall back to defaults on failure.
  515. /// </summary>
  516. private static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  517. {
  518. try
  519. {
  520. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  521. Serilog.Log.Logger = new LoggerConfiguration()
  522. .ReadFrom.Configuration(configuration)
  523. .Enrich.FromLogContext()
  524. .Enrich.WithThreadId()
  525. .CreateLogger();
  526. }
  527. catch (Exception ex)
  528. {
  529. Serilog.Log.Logger = new LoggerConfiguration()
  530. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
  531. .WriteTo.Async(x => x.File(
  532. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  533. rollingInterval: RollingInterval.Day,
  534. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"))
  535. .Enrich.FromLogContext()
  536. .Enrich.WithThreadId()
  537. .CreateLogger();
  538. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  539. }
  540. }
  541. private static void StartNewInstance(StartupOptions options)
  542. {
  543. _logger.LogInformation("Starting new instance");
  544. var module = options.RestartPath;
  545. if (string.IsNullOrWhiteSpace(module))
  546. {
  547. module = Environment.GetCommandLineArgs()[0];
  548. }
  549. string commandLineArgsString;
  550. if (options.RestartArgs != null)
  551. {
  552. commandLineArgsString = options.RestartArgs ?? string.Empty;
  553. }
  554. else
  555. {
  556. commandLineArgsString = string.Join(
  557. ' ',
  558. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  559. }
  560. _logger.LogInformation("Executable: {0}", module);
  561. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  562. Process.Start(module, commandLineArgsString);
  563. }
  564. private static string NormalizeCommandLineArgument(string arg)
  565. {
  566. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  567. {
  568. return arg;
  569. }
  570. return "\"" + arg + "\"";
  571. }
  572. }
  573. }