/// <summary>
        /// Configures the lifetime of the <see cref="IHost"/> built from <paramref name="services"/> to
        /// <see cref="SystemdLifetime"/>, provides notification messages for application started
        /// and stopping, and configures console logging to the systemd format.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     This is context aware and will only activate if it detects the process is running
        ///     as a systemd Service.
        ///   </para>
        ///   <para>
        ///     The systemd service file must be configured with <c>Type=notify</c> to enable
        ///     notifications. See <see href="https://www.freedesktop.org/software/systemd/man/systemd.service.html"/>.
        ///   </para>
        /// </remarks>
        /// <param name="services">
        /// The <see cref="IServiceCollection"/> used to build the <see cref="IHost"/>.
        /// For example, <see cref="HostApplicationBuilder.Services"/> or the <see cref="IServiceCollection"/> passed to the
        /// <see cref="IHostBuilder.ConfigureServices(System.Action{HostBuilderContext, IServiceCollection})"/> callback.
        /// </param>
        /// <returns>The <paramref name="services"/> instance for chaining.</returns>
        public static IServiceCollection AddSystemd(this IServiceCollection services)
        {
            ThrowHelper.ThrowIfNull(services);

            if (SystemdHelpers.IsSystemdService())
            {
                AddSystemdLifetime(services);
            }
            return(services);
        }
        /// <summary>
        /// Configures the <see cref="IHost"/> lifetime to <see cref="SystemdLifetime"/>,
        /// provides notification messages for application started and stopping,
        /// and configures console logging to the systemd format.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     This is context aware and will only activate if it detects the process is running
        ///     as a systemd Service.
        ///   </para>
        ///   <para>
        ///     The systemd service file must be configured with <c>Type=notify</c> to enable
        ///     notifications. See https://www.freedesktop.org/software/systemd/man/systemd.service.html.
        ///   </para>
        /// </remarks>
        /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
        /// <returns>The <paramref name="hostBuilder"/> instance for chaining.</returns>
        public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder)
        {
            ThrowHelper.ThrowIfNull(hostBuilder);

            if (SystemdHelpers.IsSystemdService())
            {
                hostBuilder.ConfigureServices((hostContext, services) =>
                {
                    AddSystemdLifetime(services);
                });
            }
            return(hostBuilder);
        }
Example #3
0
        /// <summary>
        /// Configure the logging.
        /// </summary>
        /// <param name="builder">The logger builder to configure.</param>
        /// <param name="configuration">The configuration to read settings from.</param>
        /// <param name="services">The services to read configuration from.</param>
        private void _ConfigureLogging(LoggerConfiguration builder,
                                       [CanBeNull] IConfiguration configuration,
                                       [CanBeNull] IServiceProvider services)
        {
            if (configuration != null)
            {
                try
                {
                    builder.ReadFrom.Configuration(configuration, "logging");
                }
                catch (Exception ex)
                {
                    _logger.Fatal(ex, "Could not read serilog configuration");
                }
            }

            if (services != null)
            {
                builder.ReadFrom.Services(services);
            }

            const string template =
                "[{@t:HH:mm:ss} {@l:u3} {Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1), 25} "
                + "({@i:D10})] {@m}{#if not EndsWith(@m, '\n')}\n{#end}{@x}";

            if (SystemdHelpers.IsSystemdService())
            {
                const string syslogTemplate = "[{SourceContext,-35}] {Message:lj}{NewLine}{Exception}";

                builder
                .WriteTo.Console(new ExpressionTemplate(template, theme: TemplateTheme.Code))
                .WriteTo.LocalSyslog("Kyoo", outputTemplate: syslogTemplate)
                .Enrich.WithThreadId()
                .Enrich.FromLogContext();
                return;
            }

            builder
            .WriteTo.Console(new ExpressionTemplate(template, theme: TemplateTheme.Code))
            .WriteTo.File(
                path: Path.Combine(GetDataDirectory(), "logs", "log-.log"),
                formatter: new ExpressionTemplate(template),
                rollingInterval: RollingInterval.Day,
                rollOnFileSizeLimit: true
                )
            .Enrich.WithThreadId()
            .Enrich.FromLogContext();
        }
Example #4
0
        /// <summary>
        /// Sets the host lifetime to <see cref="SystemdLifetime" />,
        /// provides notification messages for application started and stopping,
        /// and configures console logging to the systemd format.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     This is context aware and will only activate if it detects the process is running
        ///     as a systemd Service.
        ///   </para>
        ///   <para>
        ///     The systemd service file must be configured with <c>Type=notify</c> to enable
        ///     notifications. See https://www.freedesktop.org/software/systemd/man/systemd.service.html.
        ///   </para>
        /// </remarks>
        /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to use.</param>
        /// <returns></returns>
        public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder)
        {
            if (SystemdHelpers.IsSystemdService())
            {
                hostBuilder.ConfigureServices((hostContext, services) =>
                {
                    services.Configure <ConsoleLoggerOptions>(options =>
                    {
                        options.FormatterName = ConsoleFormatterNames.Systemd;
                    });

                    services.AddSingleton <ISystemdNotifier, SystemdNotifier>();
                    services.AddSingleton <IHostLifetime, SystemdLifetime>();
                });
            }
            return(hostBuilder);
        }
Example #5
0
        /// <summary>
        /// Sets the host lifetime to <see cref="SystemdLifetime" />,
        /// provides notification messages for application started and stopping,
        /// and configures console logging to the systemd format.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     This is context aware and will only activate if it detects the process is running
        ///     as a systemd Service.
        ///   </para>
        ///   <para>
        ///     The systemd service file must be configured with <c>Type=notify</c> to enable
        ///     notifications. See https://www.freedesktop.org/software/systemd/man/systemd.service.html.
        ///   </para>
        /// </remarks>
        /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to use.</param>
        /// <returns></returns>
        public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder)
        {
            if (SystemdHelpers.IsSystemdService())
            {
                hostBuilder.ConfigureServices((hostContext, services) =>
                {
                    services.Configure <ConsoleLoggerOptions>(options =>
                    {
                        options.FormatterName = ConsoleFormatterNames.Systemd;
                    });

                    // IsSystemdService() will never return true for android/browser/iOS/tvOS
#pragma warning disable CA1416 // Validate platform compatibility
                    services.AddSingleton <ISystemdNotifier, SystemdNotifier>();
                    services.AddSingleton <IHostLifetime, SystemdLifetime>();
#pragma warning restore CA1416 // Validate platform compatibility
                });
            }
            return(hostBuilder);
        }
Example #6
0
        private void DoWork(object state)
        {
            var count = Interlocked.Increment(ref this.executionCount);

            string logMessageOne = string.Format("Timed Hosted Service is working. Count: {0}", count);

            this.logger.LogInformation(logMessageOne);

            string logMessageTwo = string.Empty;

            if (SystemdHelpers.IsSystemdService())
            {
                logMessageTwo = string.Format("Running as Linux Daemon.  IsSystemdService is TRUE. Count: {0}", count);
                this.logger.LogInformation(logMessageTwo);
            }
            else
            {
                logMessageTwo = string.Format("NOT Running as Linux Daemon.  IsSystemdService is FALSE. Count: {0}", count);
                this.logger.LogInformation(logMessageTwo);
            }

            string logMessageThree = string.Empty;

            if (null != this.myConnectionStrings)
            {
                foreach (var(key, value) in this.myConnectionStrings)
                {
                    logMessageThree += $"ConnectionString :  [{key}] = {value}" + System.Environment.NewLine;
                }
            }

            this.logger.LogInformation(logMessageThree);

            string fileName = DateTime.Now.ToString("yyyy-MM-dd___HH");

            fileName = fileName.Replace(":", "--");

            string tempFileName = this.tempFileHelpers.WriteToTempFile(fileName, logMessageOne + System.Environment.NewLine + logMessageTwo + System.Environment.NewLine + logMessageThree, ".txt");

            this.logger.LogInformation(string.Format("tempFileName written. tempFileName: {0}", tempFileName));
        }
        public Worker(ILogger <Worker> logger,
                      IMessenger messenger,
                      ISerialPortManager serialport)
        {
            _logger = logger;

            _messenger = messenger;

            _serialPort = serialport;

            _serialPort.Start();

            if (SystemdHelpers.IsSystemdService())
            {
                _logger.LogInformation("Running as linux daemon");
            }
            else
            {
                _logger.LogInformation("Not running as Linux daemon");
            }
        }