2
0

Program.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
  143. serviceCollection);
  144. try
  145. {
  146. // If hosting the web client, validate the client content path
  147. if (startupConfig.HostWebClient())
  148. {
  149. string? webContentPath = appHost.ServerConfigurationManager.ApplicationPaths.WebPath;
  150. if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0)
  151. {
  152. throw new InvalidOperationException(
  153. "The server is expected to host the web client, but the provided content directory is either " +
  154. $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " +
  155. "server, you may set the '--nowebclient' command line flag, or set" +
  156. $"'{MediaBrowser.Controller.Extensions.ConfigurationExtensions.HostWebClientKey}=false' in your config settings.");
  157. }
  158. }
  159. appHost.Init();
  160. var webHost = new WebHostBuilder().ConfigureWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build();
  161. // Re-use the web host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  162. appHost.ServiceProvider = webHost.Services;
  163. await appHost.InitializeServices().ConfigureAwait(false);
  164. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  165. try
  166. {
  167. await webHost.StartAsync().ConfigureAwait(false);
  168. }
  169. catch
  170. {
  171. _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again.");
  172. throw;
  173. }
  174. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  175. stopWatch.Stop();
  176. _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed);
  177. // Block main thread until shutdown
  178. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  179. }
  180. catch (TaskCanceledException)
  181. {
  182. // Don't throw on cancellation
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.LogCritical(ex, "Error while starting server.");
  187. }
  188. finally
  189. {
  190. appHost?.Dispose();
  191. }
  192. if (_restartOnShutdown)
  193. {
  194. StartNewInstance(options);
  195. }
  196. }
  197. /// <summary>
  198. /// Call static initialization methods for the application.
  199. /// </summary>
  200. public static void PerformStaticInitialization()
  201. {
  202. // Make sure we have all the code pages we can get
  203. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  204. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  205. // Increase the max http request limit
  206. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  207. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  208. // Disable the "Expect: 100-Continue" header by default
  209. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  210. ServicePointManager.Expect100Continue = false;
  211. Batteries_V2.Init();
  212. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  213. {
  214. _logger.LogWarning("Failed to enable shared cache for SQLite");
  215. }
  216. }
  217. /// <summary>
  218. /// Configure the web host builder.
  219. /// </summary>
  220. /// <param name="builder">The builder to configure.</param>
  221. /// <param name="appHost">The application host.</param>
  222. /// <param name="serviceCollection">The application service collection.</param>
  223. /// <param name="commandLineOpts">The command line options passed to the application.</param>
  224. /// <param name="startupConfig">The application configuration.</param>
  225. /// <param name="appPaths">The application paths.</param>
  226. /// <returns>The configured web host builder.</returns>
  227. public static IWebHostBuilder ConfigureWebHostBuilder(
  228. this IWebHostBuilder builder,
  229. ApplicationHost appHost,
  230. IServiceCollection serviceCollection,
  231. StartupOptions commandLineOpts,
  232. IConfiguration startupConfig,
  233. IApplicationPaths appPaths)
  234. {
  235. return builder
  236. .UseKestrel((builderContext, options) =>
  237. {
  238. var addresses = appHost.NetManager.GetAllBindInterfaces();
  239. bool flagged = false;
  240. foreach (IPObject netAdd in addresses)
  241. {
  242. _logger.LogInformation("Kestrel listening on {0}", netAdd);
  243. options.Listen(netAdd.Address, appHost.HttpPort);
  244. if (appHost.ListenWithHttps)
  245. {
  246. options.Listen(
  247. netAdd.Address,
  248. appHost.HttpsPort,
  249. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  250. }
  251. else if (builderContext.HostingEnvironment.IsDevelopment())
  252. {
  253. try
  254. {
  255. options.Listen(
  256. netAdd.Address,
  257. appHost.HttpsPort,
  258. listenOptions => listenOptions.UseHttps());
  259. }
  260. catch (InvalidOperationException)
  261. {
  262. if (!flagged)
  263. {
  264. _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.");
  265. flagged = true;
  266. }
  267. }
  268. }
  269. }
  270. // Bind to unix socket (only on macOS and Linux)
  271. if (startupConfig.UseUnixSocket() && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  272. {
  273. var socketPath = startupConfig.GetUnixSocketPath();
  274. if (string.IsNullOrEmpty(socketPath))
  275. {
  276. var xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
  277. if (xdgRuntimeDir == null)
  278. {
  279. // Fall back to config dir
  280. socketPath = Path.Join(appPaths.ConfigurationDirectoryPath, "socket.sock");
  281. }
  282. else
  283. {
  284. socketPath = Path.Join(xdgRuntimeDir, "jellyfin-socket");
  285. }
  286. }
  287. // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
  288. if (File.Exists(socketPath))
  289. {
  290. File.Delete(socketPath);
  291. }
  292. options.ListenUnixSocket(socketPath);
  293. _logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath);
  294. }
  295. })
  296. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(commandLineOpts, appPaths, startupConfig))
  297. .UseSerilog()
  298. .ConfigureServices(services =>
  299. {
  300. // Merge the external ServiceCollection into ASP.NET DI
  301. services.Add(serviceCollection);
  302. })
  303. .UseStartup<Startup>();
  304. }
  305. /// <summary>
  306. /// Create the data, config and log paths from the variety of inputs(command line args,
  307. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  308. /// for everything else the
  309. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  310. /// is followed.
  311. /// </summary>
  312. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  313. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  314. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  315. {
  316. // dataDir
  317. // IF --datadir
  318. // ELSE IF $JELLYFIN_DATA_DIR
  319. // ELSE IF windows, use <%APPDATA%>/jellyfin
  320. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  321. // ELSE use $HOME/.local/share/jellyfin
  322. var dataDir = options.DataDir;
  323. if (string.IsNullOrEmpty(dataDir))
  324. {
  325. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  326. if (string.IsNullOrEmpty(dataDir))
  327. {
  328. // LocalApplicationData follows the XDG spec on unix machines
  329. dataDir = Path.Combine(
  330. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  331. "jellyfin");
  332. }
  333. }
  334. // configDir
  335. // IF --configdir
  336. // ELSE IF $JELLYFIN_CONFIG_DIR
  337. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  338. // ELSE IF <datadir>/config exists, use that
  339. // ELSE IF windows, use <datadir>/config
  340. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  341. // ELSE $HOME/.config/jellyfin
  342. var configDir = options.ConfigDir;
  343. if (string.IsNullOrEmpty(configDir))
  344. {
  345. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  346. if (string.IsNullOrEmpty(configDir))
  347. {
  348. if (options.DataDir != null
  349. || Directory.Exists(Path.Combine(dataDir, "config"))
  350. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  351. {
  352. // Hang config folder off already set dataDir
  353. configDir = Path.Combine(dataDir, "config");
  354. }
  355. else
  356. {
  357. // $XDG_CONFIG_HOME defines the base directory relative to which
  358. // user specific configuration files should be stored.
  359. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  360. // If $XDG_CONFIG_HOME is either not set or empty,
  361. // a default equal to $HOME /.config should be used.
  362. if (string.IsNullOrEmpty(configDir))
  363. {
  364. configDir = Path.Combine(
  365. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  366. ".config");
  367. }
  368. configDir = Path.Combine(configDir, "jellyfin");
  369. }
  370. }
  371. }
  372. // cacheDir
  373. // IF --cachedir
  374. // ELSE IF $JELLYFIN_CACHE_DIR
  375. // ELSE IF windows, use <datadir>/cache
  376. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  377. // ELSE HOME/.cache/jellyfin
  378. var cacheDir = options.CacheDir;
  379. if (string.IsNullOrEmpty(cacheDir))
  380. {
  381. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  382. if (string.IsNullOrEmpty(cacheDir))
  383. {
  384. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  385. {
  386. // Hang cache folder off already set dataDir
  387. cacheDir = Path.Combine(dataDir, "cache");
  388. }
  389. else
  390. {
  391. // $XDG_CACHE_HOME defines the base directory relative to which
  392. // user specific non-essential data files should be stored.
  393. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  394. // If $XDG_CACHE_HOME is either not set or empty,
  395. // a default equal to $HOME/.cache should be used.
  396. if (string.IsNullOrEmpty(cacheDir))
  397. {
  398. cacheDir = Path.Combine(
  399. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  400. ".cache");
  401. }
  402. cacheDir = Path.Combine(cacheDir, "jellyfin");
  403. }
  404. }
  405. }
  406. // webDir
  407. // IF --webdir
  408. // ELSE IF $JELLYFIN_WEB_DIR
  409. // ELSE <bindir>/jellyfin-web
  410. var webDir = options.WebDir;
  411. if (string.IsNullOrEmpty(webDir))
  412. {
  413. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  414. if (string.IsNullOrEmpty(webDir))
  415. {
  416. // Use default location under ResourcesPath
  417. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  418. }
  419. }
  420. // logDir
  421. // IF --logdir
  422. // ELSE IF $JELLYFIN_LOG_DIR
  423. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  424. // ELSE <datadir>/log
  425. var logDir = options.LogDir;
  426. if (string.IsNullOrEmpty(logDir))
  427. {
  428. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  429. if (string.IsNullOrEmpty(logDir))
  430. {
  431. // Hang log folder off already set dataDir
  432. logDir = Path.Combine(dataDir, "log");
  433. }
  434. }
  435. // Normalize paths. Only possible with GetFullPath for now - https://github.com/dotnet/runtime/issues/2162
  436. dataDir = Path.GetFullPath(dataDir);
  437. logDir = Path.GetFullPath(logDir);
  438. configDir = Path.GetFullPath(configDir);
  439. cacheDir = Path.GetFullPath(cacheDir);
  440. webDir = Path.GetFullPath(webDir);
  441. // Ensure the main folders exist before we continue
  442. try
  443. {
  444. Directory.CreateDirectory(dataDir);
  445. Directory.CreateDirectory(logDir);
  446. Directory.CreateDirectory(configDir);
  447. Directory.CreateDirectory(cacheDir);
  448. }
  449. catch (IOException ex)
  450. {
  451. Console.Error.WriteLine("Error whilst attempting to create folder");
  452. Console.Error.WriteLine(ex.ToString());
  453. Environment.Exit(1);
  454. }
  455. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  456. }
  457. /// <summary>
  458. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  459. /// already.
  460. /// </summary>
  461. /// <param name="appPaths">The application paths.</param>
  462. /// <returns>A task representing the creation of the configuration file, or a completed task if the file already exists.</returns>
  463. public static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  464. {
  465. // Do nothing if the config file already exists
  466. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  467. if (File.Exists(configPath))
  468. {
  469. return;
  470. }
  471. // Get a stream of the resource contents
  472. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  473. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  474. await using Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  475. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  476. // Copy the resource contents to the expected file path for the config file
  477. await using Stream dst = File.Open(configPath, FileMode.CreateNew);
  478. await resource.CopyToAsync(dst).ConfigureAwait(false);
  479. }
  480. /// <summary>
  481. /// Create the application configuration.
  482. /// </summary>
  483. /// <param name="commandLineOpts">The command line options passed to the program.</param>
  484. /// <param name="appPaths">The application paths.</param>
  485. /// <returns>The application configuration.</returns>
  486. public static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  487. {
  488. return new ConfigurationBuilder()
  489. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  490. .Build();
  491. }
  492. private static IConfigurationBuilder ConfigureAppConfiguration(
  493. this IConfigurationBuilder config,
  494. StartupOptions commandLineOpts,
  495. IApplicationPaths appPaths,
  496. IConfiguration? startupConfig = null)
  497. {
  498. // Use the swagger API page as the default redirect path if not hosting the web client
  499. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  500. if (startupConfig != null && !startupConfig.HostWebClient())
  501. {
  502. inMemoryDefaultConfig[ConfigurationExtensions.DefaultRedirectKey] = "api-docs/swagger";
  503. }
  504. return config
  505. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  506. .AddInMemoryCollection(inMemoryDefaultConfig)
  507. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  508. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  509. .AddEnvironmentVariables("JELLYFIN_")
  510. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  511. }
  512. /// <summary>
  513. /// Initialize Serilog using configuration and fall back to defaults on failure.
  514. /// </summary>
  515. private static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  516. {
  517. try
  518. {
  519. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  520. Serilog.Log.Logger = new LoggerConfiguration()
  521. .ReadFrom.Configuration(configuration)
  522. .Enrich.FromLogContext()
  523. .Enrich.WithThreadId()
  524. .CreateLogger();
  525. }
  526. catch (Exception ex)
  527. {
  528. Serilog.Log.Logger = new LoggerConfiguration()
  529. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
  530. .WriteTo.Async(x => x.File(
  531. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  532. rollingInterval: RollingInterval.Day,
  533. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"))
  534. .Enrich.FromLogContext()
  535. .Enrich.WithThreadId()
  536. .CreateLogger();
  537. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  538. }
  539. }
  540. private static void StartNewInstance(StartupOptions options)
  541. {
  542. _logger.LogInformation("Starting new instance");
  543. var module = options.RestartPath;
  544. if (string.IsNullOrWhiteSpace(module))
  545. {
  546. module = Environment.GetCommandLineArgs()[0];
  547. }
  548. string commandLineArgsString;
  549. if (options.RestartArgs != null)
  550. {
  551. commandLineArgsString = options.RestartArgs ?? string.Empty;
  552. }
  553. else
  554. {
  555. commandLineArgsString = string.Join(
  556. ' ',
  557. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  558. }
  559. _logger.LogInformation("Executable: {0}", module);
  560. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  561. Process.Start(module, commandLineArgsString);
  562. }
  563. private static string NormalizeCommandLineArgument(string arg)
  564. {
  565. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  566. {
  567. return arg;
  568. }
  569. return "\"" + arg + "\"";
  570. }
  571. }
  572. }