public static async Task <int> Main(string[] args) { ILogger logger = null; try { var host = CreateHostBuilder(args) .Build(); logger = host.Services.GetRequiredService <ILogger <Program> >(); // try to migrate database using var scope = host.Services.CreateScope(); var context = scope.ServiceProvider.GetService <ApplicationDbContext>(); await context.Database.MigrateAsync(); await host.RunAsync(); return(0); } catch (Exception ex) { logger?.LogCritical(ex, "A exception caused the service to crash."); return(1); } finally { Log.CloseAndFlush(); } }
/// <summary> /// Starts a new OpenId test server on a random generated address. /// </summary> /// <param name="outputWriter">The logger to write diagnostic messages during the lifetime of the the OpenId server.</param> public static async Task <TestOpenIdServer> StartNewAsync(ILogger outputWriter) { string address = "http://localhost:" + Random.Next(3000, 4001); IWebHost host = new WebHostBuilder() .UseUrls(address) .UseKestrel() .UseSerilog() .ConfigureServices(ConfigureServices) .Configure(Configure) .Build(); _ = Task.Run(async() => { try { await host.RunAsync(); } catch (Exception exception) { outputWriter?.LogCritical(exception, exception.Message); } }); await WaitUntilAvailableAsync(address); return(new TestOpenIdServer(address, host)); }
public static async Task Main(string[] args) { ILogger logger = null; try { var host = BuildHost(args); logger = host.Services.GetRequiredService <ILogger <Program> >(); logger?.LogInformation("Worker starting..."); await host.RunAsync(); logger?.LogInformation("Worker ended."); } catch (Exception ex) { Console.WriteLine(ex.Message); logger?.LogCritical(ex, "Worker terminated unexpectedly."); } finally { await Task.Delay(10000); } }
private static async Task StartApp(StartupOptions options) { var stopWatch = new Stopwatch(); stopWatch.Start(); ServerApplicationPaths appPaths = CreateApplicationPaths(options); // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); IConfiguration appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false); CreateLogger(appConfig, appPaths); _logger = _loggerFactory.CreateLogger("Main"); AppDomain.CurrentDomain.UnhandledException += (sender, e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); // Intercept Ctrl+C and Ctrl+Break Console.CancelKeyPress += (sender, e) => { if (_tokenSource.IsCancellationRequested) { return; // Already shutting down } e.Cancel = true; _logger.LogInformation("Ctrl+C, shutting down"); Environment.ExitCode = 128 + 2; Shutdown(); }; // Register a SIGTERM handler AppDomain.CurrentDomain.ProcessExit += (sender, e) => { if (_tokenSource.IsCancellationRequested) { return; // Already shutting down } _logger.LogInformation("Received a SIGTERM signal, shutting down"); Environment.ExitCode = 128 + 15; Shutdown(); }; _logger.LogInformation( "Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version.ToString(3)); ApplicationHost.LogEnvironmentInfo(_logger, appPaths); // Increase the max http request limit // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit); // Disable the "Expect: 100-Continue" header by default // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c ServicePointManager.Expect100Continue = false; // CA5359: Do Not Disable Certificate Validation #pragma warning disable CA5359 // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); }); #pragma warning restore CA5359 Batteries_V2.Init(); if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK) { _logger.LogWarning("Failed to enable shared cache for SQLite"); } var appHost = new CoreAppHost( appPaths, _loggerFactory, options, new ManagedFileSystem(_loggerFactory.CreateLogger <ManagedFileSystem>(), appPaths), new NullImageEncoder(), new NetworkManager(_loggerFactory.CreateLogger <NetworkManager>()), appConfig); try { await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false); appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager); await appHost.RunStartupTasksAsync().ConfigureAwait(false); stopWatch.Stop(); _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed); // Block main thread until shutdown await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false); } catch (TaskCanceledException) { // Don't throw on cancellation } catch (Exception ex) { _logger.LogCritical(ex, "Error while starting server."); } finally { appHost?.Dispose(); } if (_restartOnShutdown) { StartNewInstance(options); } }
public void Fatal(object message) { _extLogger.LogCritical(message.ToString()); }
public static async Task MainAsync(string[] args) { if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase)) { args = args.Skip(1).ToArray(); Debugger.Launch(); } NgJob job = null; ApplicationInsightsConfiguration applicationInsightsConfiguration = null; int exitCode = 0; try { // Get arguments var arguments = CommandHelpers.GetArguments(args, 1, out var secretInjector); // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled. ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // Determine the job name if (args.Length == 0) { throw new ArgumentException("Missing job name argument."); } var jobName = args[0]; var instanceName = arguments.GetOrDefault(Arguments.InstanceName, jobName); var instrumentationKey = arguments.GetOrDefault <string>(Arguments.InstrumentationKey); var heartbeatIntervalSeconds = arguments.GetOrDefault <int>(Arguments.HeartbeatIntervalSeconds); applicationInsightsConfiguration = ConfigureApplicationInsights( instrumentationKey, heartbeatIntervalSeconds, jobName, instanceName, out var telemetryClient, out var telemetryGlobalDimensions); var loggerFactory = ConfigureLoggerFactory(applicationInsightsConfiguration); InitializeServiceProvider( arguments, secretInjector, applicationInsightsConfiguration, telemetryClient, loggerFactory); job = NgJobFactory.GetJob(jobName, loggerFactory, telemetryClient, telemetryGlobalDimensions); job.SetSecretInjector(secretInjector); // This tells Application Insights that, even though a heartbeat is reported, // the state of the application is unhealthy when the exitcode is different from zero. // The heartbeat metadata is enriched with the job loop exit code. applicationInsightsConfiguration.DiagnosticsTelemetryModule?.AddOrSetHeartbeatProperty( HeartbeatProperty_JobLoopExitCode, exitCode.ToString(), isHealthy: exitCode == 0); var cancellationTokenSource = new CancellationTokenSource(); await job.RunAsync(arguments, cancellationTokenSource.Token); exitCode = 0; } catch (ArgumentException ae) { exitCode = 1; _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae); Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase()); } catch (KeyNotFoundException knfe) { exitCode = 1; _logger?.LogError("An expected key was not found. One possible cause of this is required argument has not been provided: {Exception}", knfe); Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase()); } catch (Exception e) { exitCode = 1; _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e); } applicationInsightsConfiguration.DiagnosticsTelemetryModule?.SetHeartbeatProperty( HeartbeatProperty_JobLoopExitCode, exitCode.ToString(), isHealthy: exitCode == 0); Trace.Close(); applicationInsightsConfiguration?.TelemetryConfiguration.TelemetryChannel.Flush(); }
public void LogFail(Exception ex, string message) { _writer.WriteLine($"[Fail] [{DateTimeOffset.Now:o}] {message}\n{ex}"); _logger.LogCritical(ex, message); WriteOut(); }
public static async Task <int> Main(string[] args) { StartupOptions options = new StartupOptions(args); Version version = Assembly.GetEntryAssembly().GetName().Version; if (options.ContainsOption("-v") || options.ContainsOption("--version")) { Console.WriteLine(version.ToString()); return(0); } ServerApplicationPaths appPaths = createApplicationPaths(options); // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); await createLogger(appPaths); _loggerFactory = new SerilogLoggerFactory(); _logger = _loggerFactory.CreateLogger("Main"); AppDomain.CurrentDomain.UnhandledException += (sender, e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); _logger.LogInformation("Jellyfin version: {Version}", version); EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem()); ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); SQLitePCL.Batteries_V2.Init(); // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); }); var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); using (var appHost = new CoreAppHost( appPaths, _loggerFactory, options, fileSystem, environmentInfo, new NullImageEncoder(), new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")), new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) { appHost.Init(); appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); _logger.LogInformation("Running startup tasks"); await appHost.RunStartupTasks(); // TODO: read input for a stop command // Block main thread until shutdown await ApplicationTaskCompletionSource.Task; _logger.LogInformation("Disposing app host"); } if (_restartOnShutdown) { StartNewInstance(options); } return(0); }
public void Fatal(string message, params object[] args) { _internalLogger.LogCritical(message, args); }
public async Task <ConversionStatus> ConvertPdf2Swf(string inPdfFilePath, ConversionOptions options, Func <ConversionState, ConversionStatus> checkResultAfterConversion = null) { var status = new ConversionStatus(ConversionState.ConversionFailed); try { var inputPdf = new FileInfo(inPdfFilePath); if (!inputPdf.Exists) { status.Message = "Input file doesn't exist. " + inPdfFilePath; _logger.LogError(status.Message); return(status); } //setting defaults var workingDir = options.OutputDirectory ?? inputPdf.DirectoryName; _logger.LogDebug($"Starting Conversion for file {inPdfFilePath}. Working dir {workingDir}"); var optimizedFilePath = Path.Combine(workingDir, options.OutputNamingConventions.BuildOptimizedPdfFileName(inputPdf.Name)); await OptimizePdfForConverter(inPdfFilePath, optimizedFilePath, status); if (status.State == ConversionState.OptimizationFailed) { return(status); } int numberOfPages = await GetNumberOfPages(optimizedFilePath); if (numberOfPages == 0) { var message = $"Critical failure. Can't detect number of pages for pdf: {optimizedFilePath}"; _logger.LogCritical(message); return(new ConversionStatus(ConversionState.ConversionFailed, message)); } var swfFile = Path.Combine(workingDir, options.OutputNamingConventions.BuildSwfFileName(inputPdf.Name)); var swfPagedFile = Path.Combine(workingDir, options.OutputNamingConventions.BuildPagedSwfFileName(inputPdf.Name)); if (options.OverwriteExistingSwfs) { CleanFilesBeforeConversion(options, swfFile, swfPagedFile, numberOfPages); } switch (options.HowToConvert) { case ConversionPath.OnePdf2OneSwf: status = await PerformOnePdf2OneSwfConversion(options, optimizedFilePath, swfFile, checkResultAfterConversion); break; case ConversionPath.OnePdf2PerPageSwf: status = await PerformOnePdf2ManyPagesConversion(options, inPdfFilePath, swfPagedFile, numberOfPages, checkResultAfterConversion); break; case ConversionPath.Both: status = await PerformOnePdf2OneSwfConversion(options, optimizedFilePath, swfFile); if (status.State == ConversionState.Converted || status.State == ConversionState.OutputExists) { status = await PerformOnePdf2ManyPagesConversion(options, inPdfFilePath, swfPagedFile, numberOfPages, checkResultAfterConversion, status); } break; } } catch (Exception ex) { status.Message = $"Critical failure. Converting error {ex}"; status.State = ConversionState.ConversionFailed; _logger.LogCritical(status.Message); return(status); } _logger.LogDebug($"Finishing Conversion for file {inPdfFilePath}. Status: {status.State}"); return(status); }
public void LogCritical(string message, params object[] args) => logger.LogCritical(message, args);
public void Fatal(Exception exp) { _logger.LogCritical(exp, exp.Message); }
/// <summary>Logs exception with critical log level.</summary> /// <remarks><para>See <see cref="ExceptionLoggingHelper"/> for more information.</para> /// <para>This method is null-logger-safe - if <paramref name="log"/> is null, message and exception won't be logged.</para></remarks> /// <param name="exception">Exception message to log.</param> /// <param name="log">Logger instance.</param> /// <param name="message">Log message template.</param> /// <param name="args">Structured log message arguments.</param> /// <returns>Always returns true.</returns> public static bool LogAsCritical(this Exception exception, ILogger log, string message, params object[] args) { log?.LogCritical(exception, message, args); return(true); }
public void DoWork() { logger.LogInformation("3333Doing work."); logger.LogWarning("4444Something warning"); logger.LogCritical("5555Something critical"); }
//public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) //{ // _innerLogger.LogError(string.Format(formatProvider, format, args)); //} //public void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) //{ // _innerLogger.LogError(0, exception, string.Format(formatProvider, format, args)); //} public void Fatal(string message) { _innerLogger.LogCritical(message); }
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
private static async Task StartApp(StartupOptions options) { ServerApplicationPaths appPaths = CreateApplicationPaths(options); // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); appConfig = await CreateConfiguration(appPaths).ConfigureAwait(false); CreateLogger(appConfig, appPaths); _logger = _loggerFactory.CreateLogger("Main"); AppDomain.CurrentDomain.UnhandledException += (sender, e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); // Intercept Ctrl+C and Ctrl+Break Console.CancelKeyPress += (sender, e) => { if (_tokenSource.IsCancellationRequested) { return; // Already shutting down } e.Cancel = true; _logger.LogInformation("Ctrl+C, shutting down"); Environment.ExitCode = 128 + 2; Shutdown(); }; // Register a SIGTERM handler AppDomain.CurrentDomain.ProcessExit += (sender, e) => { if (_tokenSource.IsCancellationRequested) { return; // Already shutting down } _logger.LogInformation("Received a SIGTERM signal, shutting down"); Environment.ExitCode = 128 + 15; Shutdown(); }; _logger.LogInformation("Jellyfin version: {Version}", Assembly.GetEntryAssembly().GetName().Version); EnvironmentInfo environmentInfo = new EnvironmentInfo(GetOperatingSystem()); ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); SQLitePCL.Batteries_V2.Init(); // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); }); var fileSystem = new ManagedFileSystem(_loggerFactory, environmentInfo, appPaths); using (var appHost = new CoreAppHost( appPaths, _loggerFactory, options, fileSystem, environmentInfo, new NullImageEncoder(), new NetworkManager(_loggerFactory, environmentInfo), appConfig)) { await appHost.Init(new ServiceCollection()).ConfigureAwait(false); appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager); await appHost.RunStartupTasks().ConfigureAwait(false); try { // Block main thread until shutdown await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false); } catch (TaskCanceledException) { // Don't throw on cancellation } } if (_restartOnShutdown) { StartNewInstance(options); } }
public void DoMenu(ILogger logger) { Console.WriteLine("Available examples:"); Console.WriteLine(" 1 - Getting started"); Console.WriteLine(" 2 - List AR invoices"); Console.WriteLine(" 3 - List vendors (legacy)"); Console.WriteLine(" 4 - CRUD customer"); Console.WriteLine(" 5 - Custom object function"); Console.WriteLine(" 6 - REST Getting started"); Console.WriteLine(" 7 - Exit program"); string option = ""; while (option != "7") { Console.WriteLine(""); Console.Write("Enter a number to run the example > "); option = Console.ReadLine()?.ToLower(); try { try { switch (option) { case "1": GettingStarted.Run(logger); break; case "2": Query.Run(logger); break; case "3": ListVendors.Run(logger); break; case "4": CrudCustomer.Run(logger); break; case "5": CustomObjectFunction.Run(logger); break; case "6": RestGettingStarted.Run(logger); break; case "7": Console.WriteLine("Exiting..."); LogManager.Shutdown(); break; default: Console.WriteLine("Invalid option entered"); break; } } catch (AggregateException e) { foreach (var ie in e.Flatten().InnerExceptions) { if (ie is ResponseException ex) { logger.LogCritical( "An Intacct response exception was thrown [ Class={0}, Message={1}, API Errors={2} ]", ie.GetType(), ex.Message, JsonConvert.DeserializeObject(JsonConvert.SerializeObject(ex.Errors)) ); Console.WriteLine("Failed! " + ie.Message); } else { throw ie; } } } } catch (Exception e) { logger.LogCritical( "An exception was thrown [ Class={0}, Message={1} ]", e.GetType(), e.Message ); Console.WriteLine(e.GetType() + ": " + e.Message); } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) LogManager.Flush(); } } }
public static async Task MainAsync(string[] args) { if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase)) { args = args.Skip(1).ToArray(); Debugger.Launch(); } NgJob job = null; try { // Get arguments var arguments = CommandHelpers.GetArguments(args, 1); // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled. ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // Determine the job name if (args.Length == 0) { throw new ArgumentException("Missing job name argument."); } var jobName = args[0]; TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobNameTelemetryInitializer(jobName)); // Configure ApplicationInsights ApplicationInsights.Initialize(arguments.GetOrDefault <string>(Arguments.InstrumentationKey)); // Create an ILoggerFactory var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: true); loggerConfiguration.WriteTo.File("Log.txt", retainedFileCountLimit: 3, fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true); var loggerFactory = LoggingSetup.CreateLoggerFactory(loggerConfiguration, LogEventLevel.Debug); // Create a logger that is scoped to this class (only) _logger = loggerFactory.CreateLogger <Program>(); var cancellationTokenSource = new CancellationTokenSource(); // Create an ITelemetryService var telemetryService = new TelemetryService(new TelemetryClient()); // Allow jobs to set global custom dimensions TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobPropertiesTelemetryInitializer(telemetryService)); job = NgJobFactory.GetJob(jobName, telemetryService, loggerFactory); await job.RunAsync(arguments, cancellationTokenSource.Token); } catch (ArgumentException ae) { _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae); Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase()); } catch (Exception e) { _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e); } Trace.Close(); TelemetryConfiguration.Active.TelemetryChannel.Flush(); }
public static void LogCritical(this ILogger logger, Object obj, string message, params object[] args) { Log(logger, obj, () => logger.LogCritical(message, args)); }